4

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?

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

This works. To get the text, I do this: result = foo.stdout.readlines() and 'result' has the text I want.
Use stdoutdata, stderrdata = foo.communicate() to avoid deadlocks.
2

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

3 Comments

I tried this, but it seems to choke on the '{' character. "'{' is not recognized as an internal or external command,\noperable program or batch file."
Sorry, I should have explained that.. '{' is a character in the text that the exe returns.
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."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.