简体   繁体   中英

Activate virtualenv from python or php script not SSH

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 (eg 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM