Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用subprocess.Popen执行shell脚本?_Python_Json_Bash_Shell - Fatal编程技术网

在Python中使用subprocess.Popen执行shell脚本?

在Python中使用subprocess.Popen执行shell脚本?,python,json,bash,shell,Python,Json,Bash,Shell,我正在尝试从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.loa

我正在尝试从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
回溯(最近一次呼叫最后一次):
文件“hello.py”,第29行,在
proc=subprocess.Popen(shell_脚本,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
文件“/usr/lib/python2.7/subprocess.py”,第711行,在__
错误读取,错误写入)
文件“/usr/lib/python2.7/subprocess.py”,第1308行,在执行子进程中
引发子对象异常
OSError:[Errno 2]没有这样的文件或目录

知道我在这里做错了什么吗?

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

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

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

您可以使用
shell=True
执行它(也可以省略shebang)

proc=subprocess.Popen(j['script'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
(stdout,stderr)=过程通信()

或者,你可以这样做:

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()