我如何从 python 脚本中更改当前 shell 的 venv

问题描述 投票:0回答:1

我正在尝试编写一个 python 脚本来管理各种项目的 shell 上下文。 如果我运行

user@~:source myvenv/bin/activate
它会激活
myvenv
。我想在 python 脚本中做同样的事情。

所以,如果我有名为

activate_venv
的 python 脚本。

然后我就跑了

user@~: python activate_venv
它将被激活,所有 python 路径都会改变,我的 PS1 会被正确设置为
(myvenv)user@~:

我尝试将

os.system('source myvenv/bin/activate')
输入到
activate_venv
脚本中,但它不起作用,它需要将更改应用到父进程或类似的东西。我不知道我被困住了。

我知道我可以使用别名或一般的 bash,但我希望它可以在 python 中工作,因为这只是项目管理脚本要做的一小部分。一旦我弄清楚了,

myvenv
就会是动态的。

python linux python-venv
1个回答
2
投票

解决方案1: 当前的 virtualenv 包创建一个 bin/activate_this.py 脚本,强制当前的 python 进程使用虚拟环境中的库

解决方案2: 在脚本的开头,如果调用的 python 不正确,请设置虚拟环境的环境,然后使用 os.execv 使用虚拟环境的 python 重新调用脚本。

import sys
import os
venv_path = '/path/to/your/venv'
desired_python_executable = os.path.join(venv_path, 'bin', 'python')
if sys.executable != desired_python_executable:
    import shell_source
    activate_path = os.path.join(venv_path, 'bin', 'activate')
    shell_source.source(activate_path, "bash")
    new_argv = [desired_python_executable]
    new_argv.extend(sys.argv)
    os.execv(desired_python_executable, new_argv)
# the rest of your script here.

更好的答案:

抱歉,我以为您正在尝试在 python 脚本中获取 venv 环境。 如果你想在你的 shell 环境中得到它那就更难了。 子进程无法更改父进程的环境。 这就是为什么您必须获取 bin/activate 命令而不是执行它。 这样环境设置命令就可以在父 shell 中运行。

如果您想要 shell 中的环境,我看到两个选项。

第一个是使用 os.execv 调用 shell,然后与之交互。

import shell_source
# code that dose all of the rest of your project management here
# determine the path to the activate script you want
activate_path = ...
shell_source.source(activate_path, "bash")
os.execv("/bin/bash", ["/bin/bash"])

您现在处于原始 shell 的子进程中。 因此,退出会将您带回到父 shell,而不是关闭窗口,这可以被视为好或坏。

第二个是让管理脚本的最后一个操作是写出您想要的激活脚本的路径,然后调用您的

management_script.py
as

source `python management_script.py`
© www.soinside.com 2019 - 2024. All rights reserved.