Python sub-process module subprocess detailed and application examples of the third

Source: Internet
Author: User
Tags readline stdin

Tag: Using line host read flush win 127.0.0.1 STD Use

Second, the application Example Analysis 2.1 subprocess module use 1. Subprocess.call

>>> subprocess.call (["LS", "-l"])
0
>>> Subprocess.call ("Exit 1", shell=true)
1

2. Invoke the cmd command in the system to display the results of the command execution:

X=subprocess.check_output (["echo", "Hello world!"],shell=true)

Print (x)
"Hello world!"

3. Display the contents of the file in Python:

Y=subprocess.check_output (["Type", "App2.cpp"],shell=true)

Print (y)
#include
using namespace Std;
......

4. Review 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)

5. View network settings Ipconfig-all, save to 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 .....

6. 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 method:
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 other command ')
P.stdin.flush ()
#......do something More

2.2 subprocess child process and pipeline interaction

In Python, there are many ways to interact with shell scripts and other programs, such as:
Os.system (CMD), Os.system just executes a shell command, cannot enter, and no return
Os.open (CMD), which can interact, but is one-time, calls are created and destroyed many times in a few times, performance is poor

1. For a simple example, call the LS command, there is no interaction between the two:

Import subprocess
p = subprocess. Popen (' ls ')

2. Examples of obtaining output in a program:

Import subprocess
p = subprocess. Popen (' ls ', stdout=subprocess. PIPE)
Print P.stdout.readlines ()

3. There is an example of input, output,

Parent process sends ' say hi ', child process output test say hi, parent process gets output and prints
#test1. py
Import Sys
line = Sys.stdin.readline ()
print ' Test ', line

#run. py
From subprocess Import *
P =popen ('./test1.py ', stdin=pipe,stdout=pipe)
P.stdin.write (' Say hi/n ')
Print P.stdout.readline ()

#result
Test say hi

4. Examples of continuous input and output

# test.py
Import Sys
While True:
line = Sys.stdin.readline ()
If not line:break
Sys.stdout.write (line)
Sys.stdout.flush ()

# run.py
Import Sys
From subprocess Import *
proc = Popen ('./test.py ', stdin=pipe,stdout=pipe,shell=true)
For line in Sys.stdin:
Proc.stdin.write (line)
Proc.stdin.flush ()
Output = Proc.stdout.readline ()
Sys.stdout.write (Output)
Note that flush in the run.py flush and test.py, remember to clear the buffer, or the program will not get the correct input and output

2.3 Python Gets the child process output 1 in real time. Method One

Import subprocess

def main ():
Process1 = subprocess. Popen ("Python-u sub.py", shell=false, stdout = subprocess. PIPE, Stderr=subprocess. STDOUT)


#print process1.communicate () [0]

While True:
line = Process1.stdout.readline ()
If not line:
Break
Print Line

if __name__ = = ' __main__ ':
Main ()

2. Method Two:

Import subprocess
Import time

p = subprocess. Popen (' ping 127.0.0.1-n ', stdout=subprocess. PIPE)
While p.poll () = = None:
Print P.stdout.readline ()
Time.sleep (1)
Print P.stdout.read ()
print ' Returen code: ', P.returncode

Python sub-process module subprocess detailed and application examples of the third

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.