Tutorial

Python System Command - os.system(), subprocess.call()

Published on August 3, 2022
author

Pankaj

Python System Command - os.system(), subprocess.call()

In this tutorial we will learn about Python System Command. Previously we learned about Python Random Number.

Python System Command

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.

Python os.system() function

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.

Python subprocess.call() Function

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. Python System Command

Python subprocess.check_output() function

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.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 2, 2018

I am trying to use the check_output command to call “git branch -r --merged” as follows: import subprocess import os import sys import csv cmd = “git branch -r --merged” listed_merged_branches = subprocess.check_output(cmd) print (listed_merged_branches.decode(“utf-8”)) i am getting callprocesserror Could you help please ?

- Priyasha

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 13, 2018

Please try: listed_merged_branches = subprocess.check_output(([‘git’,‘branch’,‘-r’,‘-merged’])) print (listed_merged_branches.decode(“utf-8”))

- Thiago Bezerra

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 10, 2018

    I’m pretty new to python scripting, I’m trying to achieve the python equivalent of shell cmd = “echo -e “abc\ncde” >file1” The contents of file1 then looks like this: abc cde My python script has: cmd = “echo -e \“abc\ncde\” >file” os.system(cmd) However, when executing this my file looks like this: -e abc cde -e is an option for echo to recognise \n as new line character and should not be written to the file. Is there a way around this?

    - divya

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 12, 2019

    I’m using python 3.6.8. Here’s the fix: Just wrap it in triple quotes, remove the escapes on the quotes you had and specify the path to echo, such as /bin/echo. cmd = ““”/bin/echo -e ”abc\ncde” >file”“” os.system(cmd)

    - Andy

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 26, 2019

      I am trying to run “netsh wlan start hostednetwork” command but it’s telling me You must run this command from a command prompt with administrative privilege, what can i do pls

      - Akinpelu Akinniyi

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 21, 2018

        If you just wanted to accomplish that then you could just do this: >>> text=‘abc\ncde’ >>> print(text,file=open(‘file1’,‘w’)) The file ‘file1’ will be saved to the current working directory. You can view this by: >>> import os >>> os.getcwd()

        - adk

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 22, 2019

          someone can share me the python os system need to try it this my mail.marckeef@hotmail.com

          - M

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            March 7, 2019

            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

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              March 12, 2019

              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

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 26, 2019

                with python 2 no need to decode ,

                - abdallah

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 17, 2019

                  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

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 22, 2019

                  How to solution this problem?

                  - Luis Raúl Carmona RIOS

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    September 6, 2019

                    Have you find the solution for this ?

                    - Pravi

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      May 5, 2020

                      It works fine in Python3. In case, its still not working for you, try passing the cmd string as a raw input like this : cmd = r’ps -ef|wc -l’ In that case, python will not treat the ‘|’ as special parameter (OR operator).

                      - Nandini

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        November 18, 2019

                        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

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          April 7, 2020

                          how to store os.system output to a variable and print later is it possible

                          - krishna

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          August 17, 2020

                          I have the same question too. How? The “subprocess” is returning NotADirectoryError: [Errno 20] Not a directory

                          - wantyapps

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            March 4, 2021

                            In order to capture the output generated, I will suggest you use subprocess.run() method for that e.g. ``` import subprocess as sub output = sub.run([‘ls’, ‘-l’], capture_output=True) print(output.stdout.decode()) ```

                            - Comsavvy

                              Join the Tech Talk
                              Success! Thank you! Please check your email for further details.

                              Please complete your information!

                              Become a contributor for community

                              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                              DigitalOcean Documentation

                              Full documentation for every DigitalOcean product.

                              Resources for startups and SMBs

                              The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                              Get our newsletter

                              Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                              New accounts only. By submitting your email you agree to our Privacy Policy

                              The developer cloud

                              Scale up as you grow — whether you're running one virtual machine or ten thousand.

                              Get started for free

                              Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                              *This promotional offer applies to new accounts only.