简体   繁体   中英

Activating a Python virtual environment and calling python script inside another python script

I am using pipenv for managing my packages. I want to write a python script that calls another python script that uses a different Virtual Environment(VE).

How can I run python script 1 that uses VE1 and call another python script (script2 that uses VE2).

I found this code for the cases where there is no need for changing the virtual environment.

import os
os.system("python myOtherScript.py arg1 arg2 arg3") 

The only idea that I had was simply navigating to the target project and activate shell:

os.system("cd /home/mmoradi2/pgrastertime/")
os.system("pipenv  shell")
os.system("python test.py")

but it says:

Shell for /home/..........-GdKCBK2j already activated. No action taken to avoid nested environments.

What should I do now? in fact my own code needs VE1 and the subprocess (second script) needs VE2. How can I call the second script inside my code?

In addition, the second script is used as a command line tool that accepts the inputs with flags:

python3 pgrastertime.py -s ./sql/postprocess.sql -t brasdor_c_07_0150  
-p xml -f  -r ../data/brasdor_c_07_0150.object.xml 

How can I call it using the solution of @tzaman

Each virtualenv has its own python executable which you can use directly to execute the script.

Using subprocess (more versatile than os.system ):

import subprocess

venv_python = '/path/to/other/venv/bin/python'
args = [venv_python, 'my_script.py', 'arg1', 'arg2', 'arg3']
subprocess.run(args)    

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