Linux / python · March 26, 2023 0

How to run bash script in Python?

Table of Content

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/'
result =, shell=True, stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')

In this example, script_path refers to the full path of the Bash script file. The 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 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.

%d bloggers like this: