Examples of subprocess module usage in Python
This example describes how to use the subprocess module in Python. Share it with you for your reference. The details are as follows:
Run the following command:
?
1 2 3 4 |
>>> Subprocess. call (["ls", "-l"]) 0 >>> Subprocess. call ("exit 1", shell = True) 1 |
Test and call the cmd command in the system to display the command execution result:
?
1 2 3 |
X = subprocess. check_output (["echo", "Hello World! "], Shell = True) Print (x) "Hello World! " |
The test shows the file content in python:
?
1 2 3 4 5 |
Y = subprocess. check_output (["type", "app2.cpp"], shell = True) Print (y) # Include <iostream> Using namespace std; ...... |
View the output of the ipconfig-all command and save the output to the tmp. log file:
?
1 2 |
Handle = open (r 'd: \ tmp. log ', 'wt ') Subprocess. Popen (['ipconfig', '-all'], stdout = handle) |
View the network settings ipconfig-all and save it to the variable:
?
1 2 3 4 5 6 |
Output = subprocess. Popen (['ipconfig', '-all'], stdout = subprocess. PIPE, shell = True) Oc = output. communicate () # retrieve the string from the output # Communicate () returns a tuple (stdoutdata, stderrdata ). Print (oc [0]) # print Network Information Windows IP Configuration Host Name ..... |
We can change the standard input, standard output, and standard error when creating a sub-process in Popen (), and use subprocess. PIPE connects the input and output of multiple sub-processes to form a pipeline (pipe ):
?
1 2 3 4 5 |
Child1 = subprocess. Popen (["dir", "/w"], stdout = subprocess. PIPE, shell = True) Child2 = subprocess. Popen (["wc"], stdin = child1.stdout, stdout = subprocess. PIPE, shell = True) Out = child2.communicate () Print (out) ('9 24 298 \ n', None) |
If you want to frequently communicate with the sub-thread, you cannot use communicate (); because the pipeline is closed after one communication with the sub-thread, you can try the following method:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
P = subprocess. Popen (["wc"], stdin = subprocess. PIPE, stdout = subprocess. PIPE, shell = True) P. stdin. write ('your command ') P. stdin. flush () # ...... Do something Try: # ...... Do something P. stdout. readline () # ...... Do something Except t: Print ('ioerror ') # ...... Do something more P. stdin. write ('your other command ') P. stdin. flush () # ...... Do something more |
I hope this article will help you with Python programming.