How to call a shell script from python code?

How to call a shell script from python code?

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call([sh, ./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.

There are some ways using os.popen() (deprecated) or the whole subprocess module, but this approach

import os
os.system(command)

is one of the easiest.

How to call a shell script from python code?

In case you want to pass some parameters to your shell script, you can use the method shlex.split():

import subprocess
import shlex
subprocess.call(shlex.split(./test.sh param1 param2))

with test.sh in the same folder:

#!/bin/sh
echo $1
echo $2
exit 0

Outputs:

$ python test.py 
param1
param2

Leave a Reply

Your email address will not be published. Required fields are marked *