简体   繁体   English

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

[英]executing shell script using subprocess.Popen in Python?

I am trying to execute shell script from the Python program. 我正在尝试从Python程序执行shell脚本。 And instead of using subprocess.call , I am using subprocess.Popen as I want to see the output of the shell script and error if any while executing the shell script in a variable. 而不是使用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.

But the above code whenever I am running, I am always getting error like this - 但是上面的代码每当我运行时,总是会出现这样的错误-

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

Any idea what wrong I am doing here? 知道我在这里做什么错吗?

To execute an arbitrary shell script given as a string, just add shell=True parameter. 要执行以字符串形式给出的任意shell脚本,只需添加shell=True参数。

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

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

You can execute it with shell=True (you can leave out the shebang, too). 您可以使用shell=True执行它(也可以省略shebang)。

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

Or, you could just do: 或者,您可以执行以下操作:

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

Or, you could write the script to file, then invoke it: 或者,您可以将脚本写入文件,然后调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM