shell - python 内运行子进程的问题,求解答
PHPz
PHPz 2017-04-18 09:07:11
0
2
360

我想要在 python 里开启virtualenv,然后运行一些命令,该怎么做呢?

import subprocess
p = subprocess.Popen(['source /Users/XX/Desktop/mio/worker/venv/bin/activate'],shell=True)
print p.stderr
import pika

输出如下:

None
Traceback (most recent call last):
  File "/Users/Ru/Desktop/mio/worker/run.py", line 6, in <module>
    import pika
ImportError: No module named pika


另外,我想在python内打开一个终端运行a.py,另外再打开另一个终端运行b.py。该怎么做呢?


看了subprocess和EasyProcess模块,都没有得到答案,可能我看得不够深。小白一个,希望得到解答,谢谢。

PHPz
PHPz

学习是最好的投资!

reply all(2)
Peter_Zhu

Popen will create a child process, and source /Users/XX/Desktop/mio/worker/venv/bin/activate will add some environment variables. These environment variables are only valid within the child process and will not affect the parent process.
Usually run the following command in the shell and then execute it with python:

#> source /Users/XX/Desktop/mio/worker/venv/bin/activate
#> python a.py
Ty80

About how to run other python scripts in script:

  • python2 can use execfile

  • python3 can use exec

Examples of

execfile:

# a.py
def test(x):
    return x

print(test(a))

Run through exe.py:

# exe.py
execfile('a.py', {'a':5})

Questions I answered: Python-QA

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template