简体   繁体   中英

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?

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

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