obtain the output of an external program

F

Fernando Rodriguez

Hi,

How can I save the output of an external program, called with os.system()?
 
A

Alex Martelli

Fernando said:
How can I save the output of an external program, called with os.system()?

You should use os.popen instead of os.system. It returns a file-like
object which you can read from (by default, e.g. when you call os.popen
with a single argument) and what you read is exactly the external
program's output.


Alex
 
E

Edvard Majakari

Fernando Rodriguez said:
How can I save the output of an external program, called with os.system()?

Are you sure you need to use os.system?


Python Library Documentation: module commands

NAME
commands - Execute shell commands via os.popen() and return status, output.

FILE
/usr/lib/python2.2/commands.py

DESCRIPTION
Interface summary:

import commands

outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"

A trailing newline is removed from the output string.

Encapsulates the basic operation:

pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()

[Note: it would be nice to add functions to interpret the exit status.]


--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!
One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer
Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, was
not full of lettuces. This did not seem fair. --Mr Bunnsy has an adventure
 
K

klappnase

Fernando Rodriguez said:
Hi,

How can I save the output of an external program, called with os.system()?

Use commands.getoutput() instead of os.system():

import commands
xy = commands.getoutput(external_program)

Regards

Michael
 
M

Miki Tebeka

Hello Fernando,
How can I save the output of an external program, called with os.system()?
1. Redirect the output of the program to a file (using "> fname" in
the system command) and read it later. Be aware that stderr is not
captured this way.
2. Use os.popen and variants.

IMO option 2 is better.

HTH.
Miki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top