How to run bash script in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To run a Bash script in Python, you can use the subprocess module which allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Here’s an example:

import subprocess

script_path = '/path/to/script.sh'
result = subprocess.run(script_path, shell=True, stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')
print(output)

In this example, script_path refers to the full path of the Bash script file. The subprocess.run() function runs the script file as a new process with the shell parameter set to True to indicate that the command is a shell command. The stdout parameter is set to subprocess.PIPE to capture the output of the process, which is returned as a bytes object. Finally, the decode() method is used to convert the output to a string.

Note that the subprocess module can also be used to run other types of commands or executables. The subprocess.run() function returns a CompletedProcess object, which contains information about the completed process, including its return code, stdout, and stderr.

Also, use caution when running shell scripts within Python as it can pose security risks if not implemented properly.

Tags: