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.
Activating the virtual environment in a script
Section titled “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 osimport sysimport pkg_resources
# Activate the virtual environmentactivate_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 environmentfrom module import variable
# Output HTMLprint("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
Section titled “How to use this script”-
Replace the following placeholders in the script:
username→ your Ruachost account usernameapplication→ the name of your Python applicationx.y→ Python version of the virtual environment (e.g., 2.7, 3.8)module→ a module installed in your virtual environmentvariable→ a variable or class from that module
-
Save the script in your CGI-enabled directory (e.g.,
~/public_html/script.cgi). -
Run the script from the command line or load it in a web browser:
python ~/public_html/script.cgiExpected Output
Section titled “Expected Output”If the script runs successfully, you should see a message like:
“If you see this, the module import was successful”
Section titled ““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.