This example describes the use of subprocess modules in Python. Share to everyone for your reference. Specifically as follows:
To execute a command:
?
1 2 3 4 |
>>> subprocess.call (["LS", "L"]) 0 >>> subprocess.call ("Exit 1", shell=true) 1 |
The test invokes the CMD command in the system, showing the result of the command execution:
?
1 2 3 |
X=subprocess.check_output (["Echo", "Hello world!"],shell=true) print (x) "Hello world!" |
Test to display the contents of the file 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 file Tmp.log:
?
1 2 |
Handle = Open (R ' D:tmp.log ', ' wt ') subprocess. Popen ([' ipconfig ', '-all '], Stdout=handle) |
To view network settings Ipconfig-all, save to a variable:
?
1 2 3 4 5 6 |
Output = subprocess. Popen ([' ipconfig ', '-all '], stdout=subprocess. pipe,shell=true) oc=output.communicate () #取出output中的字符串 #communicate () returns a tuple (Stdoutdata, stderrdata). Print (oc[0]) #打印网络信息 Windows IP Configuration Host Name .... |
We can change standard input, standard output, and standard error when popen () build a subprocess, and can use subprocess. Pipe joins the inputs and outputs of multiple child processes together to form a pipe (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 298n ', None) |
If you want to communicate frequently with child threads, you cannot use communicate (), because the pipe is closed after the communicate traffic. You can try the following methods:
?
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:print (' ioerror ') #......do something more p.stdin.write (' Your Command ') P.stdin.flush () #......do something more |
I hope this article will help you with your Python programming.