gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:44:01 29 4
gpt4 key购买 nike

我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。

如何运行使用 VE1 的 python 脚本 1 并调用另一个 python 脚本(使用 VE2 的脚本 2)。

我在不需要更改虚拟环境的情况下找到了此代码。

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

我唯一的想法就是导航到目标项目并激活 shell:
os.system("cd /home/mmoradi2/pgrastertime/")
os.system("pipenv shell")
os.system("python test.py")

但它说:

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



我现在该怎么办?
事实上,我自己的代码需要 VE1,而子进程(第二个脚本)需要 VE2。如何在我的代码中调用第二个脚本?

此外,第二个脚本用作接受带有标志的输入的命令行工具:
python3 pgrastertime.py -s ./sql/postprocess.sql -t brasdor_c_07_0150  
-p xml -f -r ../data/brasdor_c_07_0150.object.xml

我如何使用@tzaman 的解决方案来调用它

最佳答案

每个 virtualenv 都有自己的 python可执行文件,您可以直接使用它来执行脚本。

使用 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)

关于python - 激活 Python 虚拟环境并在另一个 Python 脚本中调用 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62218837/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com