Activating a Python virtual environment from a script file

This guide explains how to activate a Python virtual environment directly from a script, allowing you to use modules installed in that environment. This is useful for scenarios like Python CGI scripts, which are executed directly by the web server.

Important Notes

  • You must have already created a Python virtual environment and installed the required modules.

  • For applications that require Python 3, the Python Selector should be used if available.


Activating the virtual environment in a script

To activate a virtual environment from a script, use the activate_this.py file located inside the virtual environment. This allows the script to access all installed modules without manually activating the environment in the shell.

Here’s an example Python CGI script:

#!/home/username/virtualenv/application/x.y/bin/python

import os
import sys
import pkg_resources

# Activate the virtual environment
activate_this = str(os.path.dirname(sys.executable)) + '/activate_this.py'
with open(activate_this) as f:
    code = compile(f.read(), activate_this, 'exec')
    exec(code, dict(__file__=activate_this))

# Import a module from the virtual environment
from module import variable

# Output HTML
print("Content-type:text/html\r\n\r\n")
print('<html>')
print('<head>')
print('<title>Virtualenv test</title>')
print('</head>')
print('<body>')
print('<h3>If you see this, the module import was successful</h3>')
print('Python version: ' + sys.version)
print('<br/>')
print('Python executable: ' + str(sys.executable))
print('<br/>')
print('Installed modules: ')
print([p.project_name for p in pkg_resources.working_set])
print('<br/>')
print('</body>')
print('</html>')

How to use this script

  1. Replace the following placeholders in the script:

    • username → your hosting.com account username

    • application → the name of your Python application

    • x.y → Python version of the virtual environment (e.g., 2.7, 3.8)

    • module → a module installed in your virtual environment

    • variable → a variable or class from that module

  2. Save the script in your CGI-enabled directory (e.g., ~/public_html/script.cgi).

  3. Run the script from the command line or load it in a web browser:

python ~/public_html/script.cgi

Expected Output

If the script runs successfully, you should see a message like:

“If you see this, the module import was successful”

It also displays:

  • Python version

  • Path to the Python executable

  • List of installed modules

If you do not see this message, check for syntax errors or missing modules and ensure the virtual environment path is correct.

Помог ли вам данный ответ? 0 Пользователи нашли это полезным (0 голосов)

Powered by WHMCompleteSolution