capturing the output of external commands

A

Avi Kak

Is there a Python function in any of the
standard-distribution modules that does
what the backticks do in Perl?

I want to run an external command and I'd
like its output to be captured directly
in my Python script in the form of a string
object.

The function os.system() or any of the
os.exec functions do not work for what I
have in mind because they do not capture
and return in Python the output produced
by the commands supplied to them as
arguments.

Avi Kak
(e-mail address removed)
 
P

Phil Frost

See the standard 'commands' module. If that doesn't fit your needs, you
can capture the output directly with os.popen.
 
A

Avi Kak

Thanks, Phil. The function commands.getoutput()
is exactly what I was looking for.

Avi
 
P

Paul Miller

Avi Kak said:
Is there a Python function in any of the
standard-distribution modules that does
what the backticks do in Perl?

I want to run an external command and I'd
like its output to be captured directly
in my Python script in the form of a string
object.

You can fake it by redirecting the output of whatever external command
you want to run to a file, and then reading the file into a string.
It seems like kind of a hack (how does Perl's implementation actually
work for this, though?), but it will work. Package it up as a
function and you're set.
 
F

Fernando Perez

Avi said:
Is there a Python function in any of the
standard-distribution modules that does
what the backticks do in Perl?
Yes.

I want to run an external command and I'd
like its output to be captured directly
in my Python script in the form of a string
object.

In [1]: import commands

In [2]: commands.getoutput?
Type: function
Base Class: <type 'function'>
String Form: <function getoutput at 0x874a094>
Namespace: Interactive
File: /usr/lib/python2.2/commands.py
Definition: commands.getoutput(cmd)
Docstring:
Return output (stdout or stderr) of executing cmd in a shell.

You can get fancy using popen, and capture separately stdout/err, but for a
simple capture getoutput should do.

Best,

f
 

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,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top