Python: execute an external program 

Joined:
04/09/2007
Posts:
753

June 06, 2009 18:31:44    Last update: June 25, 2012 12:37:35
You can use the system call from the os module to execute an external program:
>>> import os
>>> os.system(the_command_line_string)


However, the path to the executable contains a space character, the system call treats the strings after the first space as arguments, causing an error.

Python doc recommends the use of the subprocess module:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

For example, using wget to get the google home page:
>>> from subprocess import Popen, PIPE
>>> (out, err) = Popen(['wget', '-O', '-', 'http://www.google.com'], stdout=PIPE).communicate()
--2009-06-06 13:59:39--  http://www.google.com/
Resolving www.google.com... 208.69.36.230, 208.69.36.231
Connecting to www.google.com|208.69.36.230|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `STDOUT'

    [ <=>                                   ] 4,993       --.-K/s   in 0.06s

2009-06-06 13:59:40 (78.8 KB/s) - `-' saved [4993]

>>> print out

or
>>> import subprocess
>>> subprocess.call(['curl', '-o', 'google.html', 'http://www.google.com'])
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 12446    0 12446    0     0  52923      0 --:--:-- --:--:-- --:--:--  116k
0
>>>
Share |
| Comment  | Tags