Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.6: reading data from a Windows Console application. (os.system?)

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?

like image 335
Jeremy Avatar asked Dec 29 '22 08:12

Jeremy


2 Answers

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

like image 173
YOU Avatar answered Jan 21 '23 13:01

YOU


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')
like image 43
jathanism Avatar answered Jan 21 '23 12:01

jathanism