python中执行shell脚本之subprocess模块,在执行使用Python 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.

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

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.

#!/usr/bin/env python

from subprocess import call

from textwrap import dedent

call(dedent("""\

#!/bin/bash

echo Hello world

"""), shell=True)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值