Capturing output using the subprocess module

In this section, we are going to learn about how we can capture output. We will pass PIPE for the stdout argument to capture the output. Write a script called capture_output.py and write the following code in it:

import subprocess
res = subprocess.run(['ls', '-1'], stdout=subprocess.PIPE,)
print('returncode:', res.returncode)
print(' {} bytes in stdout: {}'.format(len(res.stdout), res.stdout.decode('utf-8')))

Execute the script as follows:

student@ubuntu:~$ python3 capture_output.py

On execution, we will receive the following output:

Output:
returncode: 0
191 bytes in stdout:
1.py
accept_by_input_file.py
accept_by_pipe.py
execute_external_commands.py
getpass_example.py
ouput.txt
output.txt
password_prompt_again.py
sample_output.txt
sample.py
capture_output.py

In the preceding script, we imported the subprocess module of Python, which helps in capturing the output. The subprocess module is used for creating new processes. It also helps in connecting input/output pipes and getting return code. subprocess.run() will run the command passed as an argument. Returncode will be the exit status of your child process. In the output, if you get return code as 0, it indicates it ran successfully.

..................Content has been hidden....................

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