Skip to content

How to execute an external command or program in Python

Advertisement

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.

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.

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.

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.

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.

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.

Result:

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

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top