I am trying to activate my virtualenv using a php script or a python script but without using SSH.
This is to allow my website.com/something.py file to access certain libraries (if this can be done in another simpler way please let me know)
My PHP code is:
<?php
echo "A";
$result = exec("source ENV/bin/activate");
if ($result){
echo "Worked";
}
else{
echo "didnt work";
}
echo "B";
$result = system("python test.py");
?>
and I have test.py =
def main():
print "hello"
try:
import xlrd
except:
try:
print "xlrd didnt load"
import MySQLdb
except:
print "mdb,xlrd didnt load"
main()
The virtualenv I have setup has xlrd installed. This is the output I get on the webpage:
Adidnt workBhello xlrd didnt load
It makes sense that xlrd didnt load but why is the source command not working? This all works in SSH
According to the docs, sourcing the activate
script inside a shell just tweaks the $PATH
environment variable to point to the virtualenv's bin
directory. This script can't work from PHP, because an external executable can never modify the caller's environment for security reasons.
The documentation also tells you what you can do instead:
If you directly run a script or the python interpreter from the virtualenv's
bin/
directory (e.g.path/to/env/bin/pip
or/path/to/env/bin/python script.py
) there's no need for activation.
So you can just specify the full path to the Python installation instead:
$result = system("ENV/bin/python test.py");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With