Example 1: View the output of the Ipconfig-all command and save the output to the file Tmp.log:
= Open (R'd:\tmp.log','w') p=subprocess. Popen (['ipconfig','-all'], Stdout=handle)
If P.poll () ==none:
Print "end<<<<<<<<<<<<<<<<"
P.terminate ()
Handle.close ()
Example 2: View network Settings Ipconfig-all, save to variable:
#coding: utf-8= subprocess. Popen (['ipconfig','-all'], stdout=subprocess. pipe,shell=True) oc=output.communicate () #取出output中的字符串print oc[0] #打印网络信息
Example 3: Displaying the contents of a file t2.py
Import Subprocessy=subprocess.check_output (["type""t2.py "],shell=True" Print (y)
Example 4: Call the cmd command in the system to display the results of the command execution
Import SUBPROCESSX=subprocess.check_output (["echo"] Hello world! "],shell=True" Print (x)
Example 5: 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):
Import Subprocesschild1= subprocess. Popen (["dir","/w"], stdout=subprocess. Pipe,shell=True) child2= subprocess. Popen (["Echo","Hello"], stdin=child1.stdout,stdout=subprocess. Pipe,shell=True) out1=child1.communicate () out2=child2.communicate () print out2[0]print"********************" forIinchRange (len (OUT1)): Print Out1[i]
Example 6: If you want to communicate with a child thread frequently, you cannot use communicate (), because the communicate communication closes the pipeline once. You can try the following method:
import SUBPROCESSP=subprocess. Popen ("dir", Shell=true, stdout=subprocess. PIPE, stderr=subprocess. STDOUT) while True: = p.stdout.readline () if" and P.poll ()! = None :break
Python--subprocess