tags:

views:

105

answers:

3

how to call a shell script from python code?

+6  A: 

The subprocess module will help you out.

Here is a decent tutorial.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['./test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

Where test.sh is a simple shell script and 0 is its return value for this run.

Manoj Govindan
Note: it's preferable to pass subprocess.call() a list rather than a string (see command to Hugo24 below for the example and reasons).
Jim Dennis
@Jim: Edited my code snippet. Thanks.
Manoj Govindan
+5  A: 

There is some ways using os.popen() (deprecated) or whole subprocess module, but os.system(command) is one of the easiest.

Michał Niklas
+2  A: 

Use the subprocess module as mentioned above.

I use it like this:

subprocess.call(["notepad"])
hugo24
Note: calling subprocess with a list is safer since it doesn't necessitate passing the (potentially unsanitized) string through a shell for parsing/interpretation. The first item in the list will be the executable and all other items will be passed as arguments.
Jim Dennis