Welcome folks today in this post we will be executing shell commands
in python using subprocess
module in python. All the full source code of the application is given below.
Get Started
In order to get started we need to create an app.py
file and copy paste the following code
app.py
1 2 3 4 |
import subprocess subprocess.run(["command", "parameters"]) print("Command is executed successfully") |
So here as you can see in the above python script we are including the subprocess
built in python module and then we are executing the shell command by using the run
command or method which is present inside the subprocess
module
subprocess.run
This method takes two arguments namely the name of the command and then it takes the array of parameters so that you can pass to the command
For example
1 2 3 |
import subprocess subprocess.run(["node", "-v"]) print("The files are converted successfully") |
So here we are printing out the node.js
version using the shell command if you execute the python script now you will see the version of node.js printed out
So here as you can see it successfully execute the shell
command and prints out the version of node.js present in the system. In this way you can execute any shell
command inside your python application