Run an external program, capture output. With pipe support.
Prequisites: command line, Python hello world.
One Liner
Well, two lines if you count module import. Try it out in a python console:
$ python >>> import subprocess >>> subprocess.check_output("echo hello world", shell=True) 'hello world\n'
Yes, it’s that easy. You can also store the output in a variable.
Run Firefox, Run Anything
Obviously, you can also start graphical user interface programs from Python:
subprocess.check_output("firefox", shell=True)
Firefox starts.
Normal Pipes Supported
You can write normal shell pipes. This way, any command available in shell scripts becomes available in python.
>>> subprocess.check_output("ls /|grep bin", shell=True) 'bin\nsbin\n'
Caveats & Troubleshooting
Never trust user input. It’s best to avoid sending untrusted input to shell, or you are guaranteed to meet Bobby Tables. But if you start your python program from shell anyway, you can give yourself access to the same commands from python.
AttributeError: ‘module’ object has no attribute ‘check_output’. You need Python 2.7 or newer to use check_output(). There are other, more verbose ways of doing the same thing in older python. At least Ubuntu 12.04 has new enough python.
Error: no display specified. You can run the same commands that would work in a shell. If you can’t open firefox inside screen or over ssh in normal shell, you can’t do it from python either.
Administrivia
Tried all examples? Well done, you can now run any shell command from python.
Tested with Ubuntu 12.04 Desktop, Python 2.7.2-9ubuntu6 (2.7.3rc2).