在执行使用Python subprocess.Popen shell脚本?(executing sh

2019-10-19 04:22发布

我试图从Python程序执行shell脚本。 而不是使用subprocess.call ,我使用subprocess.Popen ,因为我想看到的shell脚本和错误的输出,如果任何,而在一个变量执行shell脚本。

#!/usr/bin/python

import subprocess
import json
import socket
import os

jsonStr = '{"script":"#!/bin/bash\\necho Hello world\\n"}'
j = json.loads(jsonStr)

shell_script = j['script']

print shell_script

print "start"
proc = subprocess.Popen(shell_script, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if stderr:
   print "Shell script gave some error"
   print stderr
else:
   print stdout
   print "end" # Shell script ran fine.

但上面的代码中,每当我跑,我总是得到错误这样的 -

Traceback (most recent call last):
  File "hello.py", line 29, in <module>
    proc = subprocess.Popen(shell_script, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

任何想法错了,我在这里做什么?

Answer 1:

为了执行给定为字符串的任意shell脚本,只需添加shell=True参数。

#!/usr/bin/env python
from subprocess import call
from textwrap import dedent

call(dedent("""\
    #!/bin/bash
    echo Hello world
    """), shell=True)


Answer 2:

您可以执行它shell=True (你可以离开了家当,太)。

proc = subprocess.Popen(j['script'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = proc.communicate()

或者,你可以只是做:

proc = subprocess.Popen(['echo', 'Hello world'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

或者,您可以编写脚本文件,然后调用它:

inf = open('test.sh', 'wb')
inf.write(j['script'])
inf.close()

print "start"
proc = subprocess.Popen(['sh', 'test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()


文章来源: executing shell script using subprocess.Popen in Python?