This article mainly introduces the subprocess module usage in Python. The example analyzes the usage skills of the subprocess module. If you need it, you can refer to the example below to describe the subprocess module usage in Python. Share it with you for your reference. The details are as follows:
Run the following command:
>>> 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:
x=subprocess.check_output(["echo", "Hello World!"],shell=True)print(x)"Hello World!"
The test shows the file content 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 tmp. log file:
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:
Output = subprocess. popen (['ipconfig', '-all'], stdout = subprocess. PIPE, shell = True) oc = output. communicate () # retrieve the string in the output # communicate () returns a tuple (stdoutdata, stderrdata ). print (oc [0]) # print the 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 ):
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:
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
I hope this article will help you with Python programming.