In this tutorial we will learn about Python System Command. Previously we learned about Python Random Number.
While making a program in python, you may need to exeucte some shell commands for your program. For example, if you use Pycharm
IDE, you may notice that there is option to share your project on github. And you probably know that file transferring is done by git, which is operated using command line. So, Pycharm executes some shell commands in background to do it. However, In this tutorial we will learn some basics about executing shell commands from your python code.
We can execute system command by using os.system() function. According to the official document, it has been said that
This is implemented by calling the Standard C function system(), and has the same limitations.
However, if command generates any output, it is sent to the interpreter standard output stream. Using this command is not recommended. In the following code we will try to know the version of git using the system command git --version
.
import os
cmd = "git --version"
returned_value = os.system(cmd) # returns the exit code in unix
print('returned value:', returned_value)
The following output found in ubuntu 16.04 where git is installed already.
git version 2.14.2
returned value: 0
Notice that we are not printing the git version command output to console, it’s being printed because console is the standard output stream here.
In the previous section, we saw that os.system()
function works fine. But it’s not recommended way to execute shell commands. We will use Python subprocess module to execute system commands. We can run shell commands by using subprocess.call()
function. See the following code which is equivalent to the previous code.
import subprocess
cmd = "git --version"
returned_value = subprocess.call(cmd, shell=True) # returns the exit code in unix
print('returned value:', returned_value)
And the output will be same also.
So far, we executed the system commands with the help of python. But we could not manipulate the output produced by those commands. Using subprocess.check_output()
function we can store the output in a variable.
import subprocess
cmd = "date"
# returns output as byte string
returned_output = subprocess.check_output(cmd)
# using decode() function to convert byte string to string
print('Current date is:', returned_output.decode("utf-8"))
It will produce output like the following
Current date is: Thu Oct 5 16:31:41 IST 2017
So, in the above sections we have discussed about basic ideas about executing python system command. But there is no limit in learning. If you wish, you can learn more about Python System command using subprocess module from official documentation.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
import subprocess # Command to execute cmd = “termux-location” # Execute Command ecmd = subprocess.check_output(cmd) # Save Output to Variable scmd = ecmd.decode(‘utf-8’) # Access data # Adjust right and left value to narrow in on desired information print(scmd[16:27])
- Eric Wess
a=os.popen("python manage.py test’').read() print(a) a---->> ’ ’
- Ahmed Elgammudi
How can we access 3rd party cli commands like executing redis-cli commands or mongodb commands, in which a new shell is popped up
- Shivam
The only way to achieve happiness is to cherish what you have and forget what you don’t have
- Salome.Taylor
how to store os.system output to a variable and print later is it possible
- krishna
Hey Guys, I am using python3.6.9, need some help here - I am coming from a perl background, trying to find a way to run a command (say for example ‘df’ command and store the output of columns 2 and 6 (size and name) in a key,value pair in a hash(dict in python world) and/or push these into a list which can be called from anywhere in the script- I have not seen very many examples of this kind of logic - any help is appreciated. Thanks
- Ubaid
Q. import subprocess cmd = “ps -ef | wc -l” returned_output = subprocess.check_output(cmd) print(returned_output.decode(“utf-8”)) not working in Case command using with pipe
- uttam kumar
with python 2 no need to decode ,
- abdallah
I want include a variable which stores the result of previous command in subprocess.Popen({“command here”],subprocess.PIPE) example: state = “here” cmd = [“”" grep -i $state /log/messages"“”]
- shruhthilaya
Hello, what if after executing command, cmd prompts something like “Press any key to continue or ctrl-c to cancel” and I basically need to somehow send any key press. Thanks for post.
- Paulius