Executing external commands and getting their output

In this section, we are going to learn about Python's subprocess module. Using subprocess, it's easy to spawn new processes and get their return code, execute external commands, and start new applications.

We are going to see how we can execute external commands and get their output in Python by using the subprocess module. We will create a script called execute_external_commands.py and write the following code in it:

import subprocess
subprocess.call(["touch", "sample.txt"])
subprocess.call(["ls"])
print("Sample file created")
subprocess.call(["rm", "sample.txt"])
subprocess.call(["ls"])
print("Sample file deleted")

Run the program and you will get the following output:

$ python3 execute_external_commands.py
Output:
1.py accept_by_pipe.py sample_output.txt sample.txt
accept_by_input_file.py execute_external_commands.py output.txt sample.py
Sample.txt file created
1.py accept_by_input_file.py accept_by_pipe.py execute_external_commands.py output.txt sample_output.txt sample.py
Sample.txt file deleted
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset