If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.
Common Way Open your command line or terminal. Navigate to the directory where your Python script lies. Run the script with the python3 script_name.py command (The keyword may change to python according to your configuration). Done.
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.
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
import os
import sys
Assuming test.sh is the shell script that you would want to execute
os.system("sh test.sh")
I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.
I give you three solutions depends on what you wanna do with the output.
1 - call script. You will see output in your terminal. output is a number.
import subprocess
output = subprocess.call(['test.sh'])
2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.
import subprocess
from subprocess import Popen, PIPE
session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()
if stderr:
raise Exception("Error "+str(stderr))
3 - call script and dump the echo commands of temp.txt in temp_file
import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
output = file.read()
print(output)
Don't forget to take a look at the doc subprocess
Use the subprocess module as mentioned above.
I use it like this:
subprocess.call(["notepad"])
I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.
The new way to execute external scripts is with the run
function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.
import subprocess
subprocess.run(['./test.sh'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With