用子进程运行单独的python程序

时间:2015-05-26 08:02:46

标签: python subprocess

我正在尝试创建一个运行我的其他python程序的脚本。我是subprocess模块的新手,所以这对我来说有点混乱。

项目结构

/qe-functional
   /qe
      /tests
         cron_functional.py
         test_web_events.py
   setup.sh

cron_functional.py

print(os.getcwd())
# print(subprocess.check_output('ls'))
runtag = "daily_run_" + datetime.today().strftime("%m_%d_%y")
testrun = "source ../../setup.sh; ./test_web_events.py -n 10 -t prf -E ctg-businessevent -p post {}".format(runtag)
cmd = testrun.split()
print(cmd)
subprocess.check_output(cmd)

输出

$ python cron_functional.py 
/Users/bli1/Development/QE/qe-functional/qe/tests
['source', '../../setup.sh;', './test_web_events.py', '-n', '10', '-t', 'prf', '-E', 'ctg-businessevent', '-p', 'post', 'daily_run_05_26_15']
Traceback (most recent call last):
  File "cron_functional.py", line 11, in <module>
    subprocess.check_output(cmd)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

1 个答案:

答案 0 :(得分:1)

source是一个内部shell命令,而不是可执行文件。你想要的不是运行带有11个参数的source命令,而是一个单线程shell脚本。您需要将整个脚本作为一个字符串传递给shell进行解释。

subprocess.check_output(testrun, shell=True)

你还没有说setup.sh做了什么。如果它正在设置环境变量并更改工作目录,请考虑在Python中执行此操作。然后你可以运行

subprocess.check_output(['./test_web_events.py', '-n', '10', …, '-p', 'post', runtag])

......不涉及外壳。