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:\n{}'.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...