In this bootcamp , we will look into how to get output from system call command and assign it to variable for later processing or output presentation.
We will use subprocess library
subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions.
The subprocess.Popen() class is responsible for the creation and management of the executed process. In contrast to the previous functions, this class executes only a single command with arguments as a list. This means that you won’t be able to pipe commands.
import subprocess process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout,stderr = process.communicate() print (stdout.decode('utf-8'))
incode above we call Popen with command argument ls , -l .
Special value that can be used as the stdin, stdout or stderr argument to
Popen and indicates that a pipe to the standard stream should be opened.
Special value that can be used as the stderr argument to
Popen and indicates that standard error should go into the same handle as standard output.
communicate() method to get the standard output and error in case as a tuple.
import subprocess process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout,stderr = process.communicate() file = open ("test.txt" , "w") file.write(stdout.decode('utf-8')) #### ON TOP IS SAMPLE OF HOW TO WRITE TO FILE