如何通过Python脚本运行lsvirtualenv或其他virtualenvwrapper函数?

3 投票
1 回答
1959 浏览
提问于 2025-04-18 15:15

我正在尝试运行 virtualenvwrapper.sh 的一些命令,比如 lsvirtualenv 和 mkvirtualenv。

我试着使用

subprocess.call(["lsvirtualenv"])

但是好像不太管用。它给了我以下的错误信息:

Traceback (most recent call last):
  File "importMaster.py", line 6, in <module>
    virtualEnvs = subprocess.call(["lsvirtualenv"])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

因为这些功能是在 virtualenvwrapper.sh 文件里面的,我该如何在 Python 脚本中引用这些功能呢?

谢谢!

1 个回答

3

你需要使用 source $(which virtualenvwrapper.sh) && <你的命令> 并且设置 shell=True

举个例子:

>>> from __future__ import print_function
>>> from subprocess import Popen, PIPE
>>> p = Popen("source $(which virtualenvwrapper.sh) && lsvirtualenv", shell=True, stdout=PIPE)
>>> print(p.stdout.read())
10leds
======


ambientlight
============

可以查看 Popen构造函数 的文档了解更多信息。

撰写回答