简体   繁体   English

激活 Python 虚拟环境并在另一个 python 脚本中调用 python 脚本

[英]Activating a Python virtual environment and calling python script inside another python script

I am using pipenv for managing my packages.我正在使用 pipenv 来管理我的包。 I want to write a python script that calls another python script that uses a different Virtual Environment(VE).我想编写一个 python 脚本,该脚本调用另一个使用不同虚拟环境 (VE) 的 python 脚本。

How can I run python script 1 that uses VE1 and call another python script (script2 that uses VE2).如何运行使用 VE1 的 python 脚本 1 并调用另一个 python 脚本(使用 VE2 的脚本 2)。

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:我唯一的想法就是导航到目标项目并激活 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. Shell for /home/...........-GdKCBK2j 已经激活。 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.事实上,我自己的代码需要 VE1,而子进程(第二个脚本)需要 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我如何使用@tzaman 的解决方案来调用它

Each virtualenv has its own python executable which you can use directly to execute the script.每个 virtualenv 都有自己的python可执行文件,您可以直接使用它来执行脚本。

Using subprocess (more versatile than os.system ):使用subprocess (比os.system更通用):

import subprocess

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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