在执行使用Python subprocess.Popen shell脚本? [英] executing shell script using subprocess.Popen in Python?
本文介绍了在执行使用Python subprocess.Popen shell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从Python程序执行shell脚本。而不是使用 subprocess.call
,我使用 subprocess.Popen
,因为我想看到的外壳输出脚本,如果有的话,同时在执行一个变量的shell脚本错误。
I am trying to execute shell script from the Python program. 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.
#!/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.
但上面的code,每当我跑,我总是得到错误这样的 -
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?
推荐答案
要执行给定为字符串的任意shell脚本,只需添加壳= TRUE
参数。
To execute an arbitrary shell script given as a string, just add shell=True
parameter.
#!/usr/bin/env python
from subprocess import call
from textwrap import dedent
call(dedent("""\
#!/bin/bash
echo Hello world
"""), shell=True)
这篇关于在执行使用Python subprocess.Popen shell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文