views:

241

answers:

2

I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly.

import os
foo = os.system('test.exe')

Assuming that test.exe returns "bar", I want the variable foo to be set to "bar". But what happens is, it prints "bar" on the console and the variable foo is set to 0.

What do I need to do to get the behavior I want?

+5  A: 

Please use subprocess

import subprocess
foo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)

http://docs.python.org/library/subprocess.html#module-subprocess

S.Mark
This works. To get the text, I do this:result = foo.stdout.readlines()and 'result' has the text I want.
Jeremy
Yeah, .readlines() or .read() will work
S.Mark
+1 for suggesting the Right Way™ to do it. :)
jathanism
Use `stdoutdata, stderrdata = foo.communicate()` to avoid deadlocks.
Sridhar Ratnakumar
A: 

WARNING: This only works on UNIX systems.

I find that subprocess is overkill when all you want is output to be captured. I recommend the use of commands.getoutput():

>>> import commands
>>> foo = commands.getoutput('bar')

Technically it's just doing a popen() on your behalf, but it's a lot simpler for this basic purpose.

BTW, os.system() does not return the output of the command, it only returns the exit status, which is why it is not working for you.

Alternatively, if you require both the exit status and the command output, use commands.getstatusoutput(), which returns a 2-tuple of (status, output):

>>> foo = commands.getstatusoutput('bar')
>>> foo
(32512, 'sh: bar: command not found')
jathanism
I tried this, but it seems to choke on the '{' character. "'{' is not recognized as an internal or external command,\noperable program orbatch file."
Jeremy
Where did "{" come from!
jathanism
Sorry, I should have explained that.. '{' is a character in the text that the exe returns.
Jeremy
Ah, well there you have it. Further inspection shows that this module is only for use on UNIX systems. I apologize for the misinformation. From the commands.py source: "# NB This only works (and is only relevant) for UNIX."
jathanism