[Tutor] Running external commands from Python

David Hutto smokefloat at gmail.com
Sat Jun 26 02:48:18 CEST 2010

On Fri, Jun 25, 2010 at 8:16 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, 26 Jun 2010 08:46:17 am Randy Kao wrote:
>> Hi all,
>> I'm a newbie to Python (switching from Perl) and had a question about
>> the best way to run external commands in Python.
> [...]
>> through: os.popen, os.popen2, os.popen3, os.system,
>> commands.getoutput()
> os.system is the oldest way, and it's pretty much obsolete.

Not to hijack  this thread, but why would accessing, what I(newbie
++1) know as the direct interface from python to the machine you're
on, be obsolete? Isn't this the direct way to access your machine
through the python 'application', if I'm using this term right?

Only use it
> for quick-and-dirty scripts when you're too lazy to do the right thing
> and don't care who knows it. It doesn't capture either stdin or stdout,
> only the return value.
> os.popen, popen2 and popen3 are probably closer to what you're used to
> in Perl. They basically differ in how many file handles they return:
> popen returns the external command's stdout as a file handle.
> popen2 returns (stdin, stdout)
> popen3 returns (stdin, stdout, stderr)
> The commands module is meant as an easier to use front end to the popen*
> functions, for times where popen* are too much and system is too
> little. If all you want is the output (stdout + stderr) of an external
> command:
> import commands
> output = commands.getoutput('ls -l foo*')
> will do the trick.
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list