How can I call an external command in Python?
Look at the subprocess module in the stdlib:
The advantage of subprocess vs system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...). I think os.system is deprecated, too, or will be: http://docs.python.org/library/subprocess.html#replacing-older-functions-with-the-subprocess-module For quick/dirty/one time scripts, |
|||||||||||||||||||||
|
Here's a summary of the ways to call external programs and the advantages and disadvantages of each:
The |
|||||||||||||||||||||
|
I typically use:
You are free to do what you want with the stdout data in the pipe. In fact, you can simply omit those parameters (stdout= and stderr=) and it'll behave like os.system(). |
|||||||||||||||||||||
|
Some hints on detaching the child process from the calling one (starting the child process in background). Suppose you want to start a long task from a CGI-script, that is the child process should live longer than the CGI-script execution process. The classical example from the subprocess module docs is:
The idea here is that you do not want to wait in the line 'call subprocess' until the longtask.py is finished. But it is not clear what happens after the line 'some more code here' from the example. My target platform was freebsd, but the development was on windows, so I faced the problem on windows first. On windows (win xp), the parent process will not finish until the longtask.py has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same. The solution is to pass DETACHED_PROCESS flag to the underlying CreateProcess function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:
On freebsd we have another problem: when the parent process is finished, it finishes the child processes as well. And that is not what you want in CGI-script either. Some experiments showed that the problem seemed to be in sharing sys.stdout. And the working solution was the following:
I have not checked the code on other platforms and do not know the reasons of the behaviour on freebsd. If anyone knows, please share your ideas. Googling on starting background processes in Python does not shed any light yet. |
|||||||||||||||||
|
I'd recommend using the subprocess module instead of os.system because it does shell escaping for you and is therefore much safer: http://docs.python.org/lib/module-subprocess.html
|
|||||||||
|
Check "pexpect" python library, too. It allows for interactive controlling of external programs/commands, even ssh, ftp, telnet etc. You can just type something like:
|
|||||
|
I always use
But this seem to be a good tool: Look an example:
|
|||||
|
If you want to return the results of the command you need os.popen: |
|||
|
If what you need is the output from the command you are calling you can use subprocess.check_output since Python 2.7
|
|||
|
This is how I run my commands. This code has everything you need pretty much
|
|||||
|
without the output of result
with output of result
|
|||||
|
os.system is OK, but kind of dated. It's also not very secure. Instead, try subprocess. subprocess does not call sh directly and is therefore more secure than os.system. Get more information at http://docs.python.org/lib/module-subprocess.html |
|||
|
I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans. Example usage from the readme:
Pipe stuff around too:
|
|||
|
In case you need to go only with standard library, use subprocess module:
It is the recommended standard way. However, more complicated tasks (pipes, output, input, etc.) can be tiring to construct and write. If you do not mind external dependencies, install and use sh:
It is the best and the most developer-friendly |
|||
|
Note that this is dangerous, since the command isn't cleaned. I leave it up to you to google for the relevant docs on the 'os' and 'sys' modules. There are a bunch of functions (exec* , spawn*) that will do similar things. |
|||
|
os.system has been superceeded by the subprocess module. Use subproccess instead. |
|||||
|
|
|||
|
|
||||
|
There are a lot of different ways to run external commands in python, and all of them have their own plus sides and drawbacks. My colleagues and me have been writing python sysadmin tools, so we need to run a lot of external commands, and sometimes you want them to block or run asynchronously, time-out, update every second... There are also different ways of handling the return code and errors, and you might want to parse the output, and provide new input (in an expect kind of style) Or you will need to redirect stdin, stdout and stderr to run in a different tty (e.g., when using screen) So you will probably have to write a lot of wrappers around the external command. So here is a python module which we have written which can handle almost anything you would want, and if not, it's very flexible so you can easily extend it: https://github.com/hpcugent/vsc-base/blob/master/lib/vsc/utils/run.py |
||||
|
http://www.python.org/doc/2.5/lib/module-subprocess.html ...or for a very simple command:
|
|||
|
There is another difference here which is not mentioned above. subprocess.Popen executes the as a subprocess. In my case, I need to execute file which needs to communicate with another program . I tried subprocess, execution was successful. However could not comm w/ . everything normal when I run both from the terminal. One more: (NOTE: kwrite behaves different from other apps. If you try below with firefox results will not be the same) If you try os.system("kwrite"), program flow freezes until user closes kwrite. To overcome that I tried instead os.system(konsole -e kwrite). This time program continued to flow but kwrite became the subprocess of the konsole. Anyone runs the kwrite not being a subprocess (i.e. at the system monitor it must be appear at the leftmost edge of the tree) Thanks |
|||
|
you can use Popen, then you can check procedure's status
Check this out subprocess.Popen |
|||
|
Just to add to the discussion, if you include using a Python console, you can call external commands from ipython. While in the ipython prompt, you can call call shell commands by prefixing '!'. You can also combine python code with shell, and assign the output of shell scripts to python variables. For instance:
|
|||
|
Very simplest way to run any command and get result back:
|
|||||
|
I quite like shell_command for its simplicity. It's built on top of the subprocess module. |
|||
|
The subprocess module described above by Eli is very powerful, but the syntax to make a bog-standard system call and inspect its output, is unnecessarily prolix. The easiest way to make a system call is with the commands module (Linux only).
The first item in the tuple is the return code of the process. The second item is its standard output (and standard error, merged). The Python devs have 'deprecated' the commands module, but that doesn't mean you shouldn't use it. Only that they're not developing it anymore, which is okay, because it's already perfect (at its small but important function). |
|||||||||||||||||
|
After some research, I have the following code which works very well for me. It basically prints both stdout and stderr in real time. Hope it helps someone else who needs it.
|
|||
|
You can do with subprocess module
or
|
|||||||||
|
protected by Martijn Pieters Apr 16 '13 at 20:23
This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.