Execute an existing bash script using Python subprocess module
We can also execute an existing a bash script using Python subprocess module.
Python3
import subprocess # If your shell script has shebang, # you can omit shell=True argument. print (subprocess.run([ "/path/to/your/shell/script" , "arguments" ], shell = True )) |
Output:
CompletedProcess(args=['/path/to/your/shell/script', 'arguments'], returncode=127)
Common problems with invoking shell script and how to solve them:
- Permission denied when invoking script — don’t forget to make your script executable! Use chmod +x /path/to/your/script
- OSError: [Errno 8] Exec format error — run functions lacks shell=True option or script has no shebang.
How to run bash script in Python?
If you are using any major operating system, you are indirectly interacting with bash. If you are running Ubuntu, Linux Mint, or any other Linux distribution, you are interacting with bash every time you use the terminal. Suppose you have written your bash script that needs to be invoked from python code. The two common modules for interacting with the system terminal are os and subprocess module.
Let’s consider such a simple example, presenting a recommended approach to invoking subprocesses. As an argument, you have to pass the command you want to invoke and its arguments, all wrapped in a list.