Search code examples
pythonsubprocessvirtual-environment

Source a virtual environment using python


On the servers I am working on, there is a virtual environment which can be activated using source /bin/virtualenv-activate. I need this virtual environment because of a command line tool which is accessible only there. Let's call it fancytool. What I would like to do is to use fancytool out of a python script and return its output into a python variable. The python script is not initiated in the virtual environment, so I thought of something like this:

os.system('source /bin/virtualenv-activate')
results = os.popen(fancytool).read()

However, this returns:

sh: 1: source: not found
sh: 1: fancytool: not found

If I enter source /bin/virtualenv-activate in the terminal and then fancytool, everything works fine. How can I achieve this also in a python script?


Solution

  • You should add a shebang to the top of the script to activate the env

    #!/path/to/venv/bin/python 
    
    # your code here
    

    However relying on the knowledge of the venv within your scripts is considered poor practice