Python 2.6: reading data from a Windows Console ap

2020-07-18 09:32发布

问题:

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?

回答1:

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



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