This example describes the use of the subprocess module in Python. Share to everyone for your reference. Specific as follows:
Execute command:
>>> subprocess.call (["LS", "-l"]) 0>>> Subprocess.call ("Exit 1", shell=true) 1
The cmd command in the test call system shows the result of the command execution:
X=subprocess.check_output (["Echo", "Hello world!"],shell=true) print (x) "Hello world!"
The test displays the contents of the file in Python:
Y=subprocess.check_output (["Type", "App2.cpp"],shell=true) print (y) #include
using namespace std; ......
View the output of the Ipconfig-all command and save the output to the file Tmp.log:
Handle = Open (R ' D:\tmp.log ', ' wt ') subprocess. Popen ([' ipconfig ', '-all '], Stdout=handle)
To view the network settings Ipconfig-all, save to the variable:
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 () is established, and can take advantage of subprocess. Pipes connect the inputs and outputs of multiple sub-processes together to form a pipeline (pipe):
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 298\n ', None)
If you want to communicate with the child threads frequently, you cannot use communicate (), because the communicate communication closes the pipeline once. You can try the following methods:
P= subprocess. Popen (["WC"], stdin=subprocess. Pipe,stdout=subprocess. pipe,shell=true) p.stdin.write (' Your Command ') P.stdin.flush () #......do somethingtry: #......do something P.stdout.readline () #......do somethingexcept: print (' IOError ') #......do something Morep.stdin.write (' Your other command ') P.stdin.flush () #......do something more
Hopefully this article will help you with Python programming.