Detailed Python3 subprocess realization of pipeline pipe pipe interactive operation read/write communication method

Source: Internet
Author: User
Here we use the shell under Windows for example:

Subprocess  *

To make it easy for you to understand, we use a very simple piece of code to illustrate:

You can see that we instantiated a P with Popen, created the subroutine Cmd.exe, and then we gave his stdin (standard input stream) Stdout (standard output stream);

The subprocess is also used. PIPE as a parameter, this is a special value that is used to indicate that these channels are open. (in Python3.5, the Run () method is added for better operation)

And then we go on.

Does this information look familiar? This is the standard output of CMD!

Then it will output these:

The information we just wrote "Echo hellwworlds\r\n" has been written, and it seems to have succeeded!

Note that we use the P.stdin.flush () to refresh the input buffer, the output of the information also needs a "\ r \ n", at least in the Windows system must do this, or only refresh (P.stdin.flush) is not valid;

What the hell have we done?

We successfully created the subroutine Cmd.exe and wrote "Echo hellwworlds\r\n", then Cmd gets and executes, then returns Hellwworlds, which is a very simple read-write interaction!

More advanced use

Now that we can simply read and write, then add for and threading bar, the taste may be better oh ~

#run. py from  subprocess Import * Import threading Import TIMEP =popen (' cmd.exe ', shell=true,stdin=pipe,stdout=pipe) def run ():    global P while    True: line        = P.stdout.readline ()         If the line:  #空则跳出            break        Print (">>>>>>", Line.decode ("GBK"))    Print ("Look up!!! EXIT = = = ")   #跳出w =threading. Thread (Target=run) p.stdin.write ("Echo hellw_world!\r\n". Encode ("GBK")) P.stdin.flush () Time.sleep (1) # Latency is due to waiting for thread-ready p.stdin.write ("exit\r\n". Encode ("GBK")) P.stdin.flush () W.start ()

Well, well, guess what the output is?

There are a lot of line breaks because the cmd returns a newline, and then the print output adds a newline, so instead of two lines, you can consider using Sys.stdout.write to output, so there's no additional line breaks.

In this case, you can make a basic reading and writing, then we begin to encapsulate it.

Package pipe

No nonsense, directly on the code, if you really want to learn the words, also please carefully read the code yourself.

110 rows

We have implemented the process of centralizing all the processes within a class, and can define three parameters, exit feedback functions, ready feedback functions, and output feedback functions.

#-*-Coding:utf-8-*-import subprocess import sysimport threadingclass loopexception (Exception): "" "Loop exception custom exception, this exception does not represent Each cycle is an abnormal exit "" "Def __init__ (self,msg=" Loopexception "): Self._msg=msg def __str__ (self): return to self.        _msgclass swpipe (): "" "communicates with any child process pipeline class, can be piped interactive communication" "" Def __init__ (Self,commande,func,exitfunc,readyfunc=none, Shell=true,stdin=subprocess. Pipe,stdout=subprocess. Pipe,stderr=subprocess.        Pipe,code= "GBK"): "" "commande command func correct output feedback function Exitfunc Exception feedback function Readyfunc called when pipeline creation is complete "" "Self._thread = Threading.  Thread (target=self.__run,args= (commande,shell,stdin,stdout,stderr,readyfunc)) Self._code = Code Self._func = Func Self._exitfunc = Exitfunc Self._flag = False SELF._CRFL = "\ r \ n" def __run (Self,commande,she Ll,stdin,stdout,stderr,readyfunc): "" "Private Function" "" try:self._process = subprocess.            Popen (commande,    Shell=shell, Stdin=stdin, Stdout=stdout, Stderr=stderr) Except OSError as E:self._exitfunc (e) fun = Self._process.stdout.readline Self._flag = T Rue if Readyfunc! = none:threading.                  Thread (Target=readyfunc). Start () #准备就绪 While true:line = Fun () If not line:                Break try:tmp = Line.decode (self._code) except Unicodedecodeerror: TMP = \ SELF._CRFL + "[Pipe_code_error] <code error:unicodedecodeerror>\n" + "[PIP E_code_error] Now CODE is: "+ Self._code + SELF._CRFL self._func (self,tmp) Self._flag = False SE Lf._exitfunc (Loopexception ("While Loop Break")) #正常退出 def write (self,msg): if Self._flag: #请注意一下这里的 NewLine Self._process.stdin.write (msg + SELF._CRFL). Encode (Self._code)) sElf._process.stdin.flush () #sys. Stdin.write (msg) #怎么说呢, cannot send instructions directly in code, only the default stdin else:raise Loop  Exception ("Shell pipe error from ' _flag ' not true!")         #还未准备好就退出 def start: "" "Start Thread" "" Self._thread.start () def destroy (self): "" "" "" "" "    Process.stdout.close () Self._thread.stop () del self if __name__ = = ' __main__ ': #那么我们来开始使用它吧 E = None #反馈函数 def event (cls,line): #输出反馈函数 Sys.stdout.write (line) def exit (msg): #退出反馈函数 Print (ms g) def ready (): #线程就绪反馈函数 e.write ("dir") #执行 e.write ("ping www.baidu.com") e.write ("Echo hello! Hello China! Hello World! ") E.write (" Exit ") E = Swpipe (" cmd.exe ", Event,exit,ready) E.start ()

Output:

As you can see, our instructions are executed in sequence. Of course, there's the OS in there.

So your extensible pipe class should already be built, right?

A: The reason why I want to add the number of rows in front of this code is to prevent you from copying it, because you may never understand what's going on here, but only know how to use it.

By the way:

It's best to refer to the official documentation, which has been very detailed. Subprocess.Popen.communicate may be more suitable for you to see what you are going to do.

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.