• Uncategorized

About python : How-to-redirect-output-of-a-subprocess-to-a-file

Question Detail

I have the following python script:

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

I want to redirect the output of the subprocess to the file response.xml. In the next step I want to parse the contents of response.xml. So it must be closed before we can parse. But, after executionresponse.xmlends up being blank and I'm getting error in the linetree = ET.parse(…)`. I also tried:

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

This doesn’t work either. Please can someone help

Question Answer

The > is a shell feature but Popen() does not use a shell by default. You should be able to fix by using a shell explicitely:

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

However I’d advise not to use a shell (for better security) and write the contents to a file using pure Python:

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

Here is a sample which opens a file for writing/reading:

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.