search

Home  >  Q&A  >  body text

shell - python 内运行子进程的问题,求解答

我想要在 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模块,都没有得到答案,可能我看得不够深。小白一个,希望得到解答,谢谢。

PHPzPHPz2891 days ago365

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 09:09:11

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:09:11

    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

    reply
    0
  • Cancelreply