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.


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.


Python Example with Shell Expansion

The default 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: 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.