Python 如何将子流程的输出重定向到文件
我有以下python脚本:Python 如何将子流程的输出重定向到文件,python,python-2.7,subprocess,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]
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的内容。所以必须先关闭它,然后才能解析。但是,在执行之后
response.xml最后是空的,我在
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()
这也不行。请有人帮忙,这个
是一个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)
下面是一个打开文件进行写入/读取的示例:
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()