How to run bash script in Python?
Last Updated :
13 Sep, 2022
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.
Running simple bash script on terminal using Python
Python3
import os
os.system("echo GeeksForGeeks")
Output:
GeeksForGeeks
Executing bash scripts using Python subprocess module
A new process is created, and command echo is invoked with the argument "Geeks for geeks". Although, the command's result is not captured by the python script. We can do it by adding optional keyword argument capture_output=True to run the function, or by invoking check_output function from the same module. Both functions invoke the command, but the first one is available in Python3.7 and newer versions.
Python3
import subprocess
# From Python3.7 you can add
# keyword argument capture_output
print(subprocess.run(["echo", "Geeks for geeks"],
capture_output=True))
# For older versions of Python:
print(subprocess.check_output(["echo",
"Geeks for geeks"]))
Output:
CompletedProcess(args=['echo', 'Geeks for geeks'], returncode=0, stdout=b'Geeks for geeks\n', stderr=b'')
b'Geeks for geeks\n'
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.
Executing bash command using Python os module
Using os module also, we can execute bash command. Here, we have executed a bash command to find the current date.
Python3
import os
os.system('date +"Today is: %A %d %B"')
Output:
Today is: Friday 02 September
Similar Reads
How to Run a Python Script Python scripts are Python code files saved with a .py extension. You can run these files on any device if it has Python installed on it. They are very versatile programs and can perform a variety of tasks like data analysis, web development, etc. You might get these Python scripts if you are a begin
6 min read
How To Run Bash Script In Linux? Bash scripts, also called shell scripts, are programs that help automate tasks by storing a series of commands that often go together, like updates or upgrades. These scripts make it easier to perform tasks automatically instead of typing each command manually. After creating a Bash script, you can
6 min read
How to Run Python Script in GitHub Actions ? A tool available on GitHub that can help you automate chores in your software projects is called GitHub Actions. It enables you to design workflows that, when executed automatically, carry out actions like as deploying, testing, and even sending out notifications. It basically works like a small rob
6 min read
How to Run Bash Script in AWS Lambda AWS Lambda is one of the strongest computing services in the serverless domain, via which developers can run their code without the need to provision or manage servers. Writing your code with AWS Lambda is key; AWS takes care of the needed infrastructure for running it. This makes it an excellent ch
7 min read
How To Embed Python Code In Batch Script Embedding Python code in a batch script can be very helpful for automating tasks that require both shell commands and Python scripting. In this article, we will discuss how to embed Python code within a batch script. What are Batch Scripts and Python Code?Batch scripts are text files containing a se
4 min read
How to Run a Python Script using Docker? Docker helps you to run your Python application very smoothly in different environments without worrying about underlying platforms. Once you build an image using dockerfile you can run that image wherever you want to run. Docker image will help you to package all the dependencies required for the a
8 min read
How To Run Python Script In Kubernetes Pod ? Execution of Python scripts helps in bringing the automation of work. Bringing these Python scripts into containerization as containerized applications will enhance the seamless performance and facilitate with high availability and scalability of the application. In this article, we guide you on how
5 min read
How to setup Notepad to run Python Script Due to its simplicity, versatility, and readability, Python has become phenomenally popular as a computer language that is highly leveled and dynamically typed. These are some of the IDEs for Python development that have many tools; however, if you are just starting or want it lighter, then Windowsâ
2 min read
Is Bash Script Better Than Python Programming languages let you create programs and various online solutions like web apps, games, mobile apps, etc. There are multiple computer languages online that you can use to automate, assemble, interpret, and manage data processing. Programming languages like Bash and Python are prevalent amon
6 min read
Run python script from anywhere in linux In Linux, there is a way to execute python files from anywhere. This can be done by typing several commands in the terminal. Prerequisite: Basic Shell Commands in Linux Basics of python Steps: At first, open the terminal and go to the home directory. To go the home directory type the following comma
2 min read