使用 python 获取虚拟环境

Source a virtual environment using python

在我工作的服务器上,有一个可以使用 source /bin/virtualenv-activate 激活的虚拟环境。我需要这个虚拟环境,因为命令行工具只能在那里访问。我们称它为 fancytool。我想做的是使用 python 脚本中的 fancytool 并将其输出 return 到 python 变量中。 python脚本在虚拟环境中没有启动,所以我想到了这样的事情:

os.system('source /bin/virtualenv-activate')
results = os.popen(fancytool).read()

但是,这个 returns:

sh: 1: source: not found
sh: 1: fancytool: not found

如果我在终端输入 source /bin/virtualenv-activate 然后输入 fancytool,一切正常。我怎样才能在 python 脚本中实现这一点?

您应该在脚本顶部添加一个 shebang 以激活环境

#!/path/to/venv/bin/python 

# your code here

然而,依赖脚本中的 venv 知识被认为是糟糕的做法