如何将子进程的输出重定向到文件

时间:2014-05-28 08:05:23

标签: python python-2.7 subprocess

我有以下python脚本:

import shlex
import subprocess
from datetime import datetime,timedelta
import os
import sys
import xml.etree.ElementTree as ET


time = (datetime.now()- timedelta(hours=6)).strftime('%Y-%m-%dT%H:%M:%S') 
#print time

path = sys.argv[1]

os.chdir(path + '/src/MarketplaceWebServiceOrders/Samples')


cmd = "php -f ListOrders.php %s > response.xml" %(time)
print cmd
args = shlex.split(cmd)
p = subprocess.Popen(args)
p.wait()
respFile = open("response.xml")
respFile.close()

tree = ET.parse(path + '/src/MarketplaceWebServiceOrders/Samples/response.xml')
root = tree.getroot()

我想将子流程的输出重定向到文件response.xml。在下一步中,我想解析response.xml. So it must be closed before we can parse. But, after execution response.xml ends up being blank and I'm getting error in the line tree = ET.parse(...)`的内容。我也尝试过:

respFile = open("response.xml","w")

cmd = "php -f ListOrders.php %s > %s" %(time,respFile)
print cmd
args = shlex.split(cmd)
p = subprocess.Popen(args)
p.wait()
respFile.close()

这也不起作用。请有人帮忙

2 个答案:

答案 0 :(得分:2)

>是shell功能,但默认情况下Popen()不使用shell。您应该能够明确地使用shell来修复:

p = subprocess.Popen(args, shell=True)

但是我建议不要使用shell(为了更好的安全性)并使用纯Python将内容写入文件:

p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True)
(stdout, stderr) = p.communicate()
with file('response.xml', 'w') as fp:
    fp.write(stdout)

答案 1 :(得分:0)

以下是打开文件进行书写/阅读的示例:

import subprocess

with open('out.txt', 'w+') as f:
    cmd = ['/bin/ls', '/']
    p = subprocess.Popen(cmd, stdout=f)
    p.communicate()

    # Read from the file
    f.seek(0)
    for line in f:
        print line.strip()