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.
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 librarycall 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
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
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
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
2 Comments
Awesome article. Can I execute shell script from Python script?
Very helpful. Thanks