Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»Python»How to execute an external command or program in Python

    How to execute an external command or program in Python

    By RahulJuly 25, 20222 Mins Read

    The Python subprocess module allows to spawn of new processes, and execute external commands or scripts from the Python scripts. You can install the latest version of Python using these tutorials. Also, there is a number of IDE available for Python. Like Install PyCharm Python IDE on Ubuntu systems.

    Advertisement

    Python Scrpt to Call System Command

    Let’s create your first program to list all files available in the current directory. You can add any number of command-line parameters with the comm (,) separated.

    1
    2
    3
    4
    #!/usr/bin/python3
     
    import subprocess
    subprocess.call(["ls", "-l"])

    Where-

    • import statement is used to load the subprocess module form the Python standard library
    • call is the function of subprocess module, is used to execute external commands

    Python Print without New Line

    Python commands terminate with new line output “\n”, which you can overwrite using end=”” means that the next command output will be on the same line. See the below example.

    1
    2
    3
    4
    5
    6
    #!/usr/bin/python3
     
    import subprocess
     
    print("\nToday is ", end="")
    subprocess.call(["date","+%D"])

    Result:

    Today is 01/11/18
    

    Python Example with Shell Expansion

    The default subprocess.call doesn’t expand shell wildcards or perform command substitution. This can be overridden by passing True value for shell argument. Remember that the use of shell=True could be a security issue for your system by executing the harmful command.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/python3
     
    import subprocess
     
    # Executing command without shell expansion
    subprocess.call(['echo', 'Welcome $USER'])
     
    # Executing a command with shell expansion
    subprocess.call('echo Welcome $USER', shell=True)

    Result:

    Welcome $USER
    Welcome root
    

    You can see in the above output that the first command prints a variable name because it was executed without shell expansion. The second command executed with shell expansion get the value of the USER environment variable. Also, you can see that the entire command is now passed as a string and not as a list of strings.

    Other Useful Python Examples

    You can make your scripts more readable format and beautiful by storing a long command in a variable and then execute it.

    1
    2
    3
    4
    5
    6
    #!/usr/bin/python3
     
    import subprocess
     
    cmd = "grep -Re 'Fatal' /var/log/ > searches.txt"
    subprocess.call(cmd, shell=True)

    You can also store the output of any command to a variable using subprocess.getoutput. This will also store if any error message is generated.

    1
    2
    3
    4
    5
    6
    7
    8
    #!/usr/bin/python3
     
    import subprocess
     
    print("The output of 'pwd' command is:", flush=True)
     
    output = subprocess.getoutput('pwd')
    print(output)

    Result:

    The output of 'pwd' command is:
    /root/Python/Scripts
    

    command Python shell
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Split Command in Linux With Examples (Split Large Files)

    tail Command in Linux with Examples

    How to Install Python 3.11 on Amazon Linux 2

    View 2 Comments

    2 Comments

    1. Sanjay Mishra on January 13, 2018 4:01 am

      Awesome article. Can I execute shell script from Python script?

      Reply
    2. Denial on January 13, 2018 3:59 am

      Very helpful. Thanks

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Split Command in Linux With Examples (Split Large Files)
    • Test Your Internet Speed from the Linux Terminal
    • 11 Practical Example of cat Command in Linux
    • sleep Command in Linux with Examples
    • 20 Basic Linux Commands for the Beginners (Recommended)
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.