Python gets the output of CMD in real time

Source: Internet
Author: User
Recently found a problem, a man wrote the console program is not strong enough to listen to the socket when prone to collapse, resulting in the overall program of the crash, but he did not find a solution to the problem, has been resolved, but this is a monitoring process, or more important, and must find a way to solve.

(This is to kill my rhythm ah ....) Because the individual does not understand the language he uses, it can only be done on the outside of the program.

Environment Description:

1. When the target program executes, it listens on 8080 ports, TCP, and outputs the client IP address through the console after each client connection.

2. Monitoring is not done at once, but is always listening, the program will not quit

3. In order to monitor the need, it is best to sort and organize the connected IP.

P.S. The system is based on the Windows platform.

Remember to do the monitoring program, simple point is better, so think of Python.

My expected logic is this, through the python detection of the target program is broken, if the bid to start the target program, and monitoring, each output, Python once the data processing, and then loop.

The first step is to take care of the output capture problem first.

# This method was used for Monitoringimport timeimport subprocessimport localeimport codecsmylist = []ps = subprocess. Popen (' Netstat-a ', stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Shell=true) while True:  data = Ps.stdout.readline ()  if data = = B ":    if Ps.poll () is not None:      break< C4/>else:    mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name))    NewList = [] For    i in MyList:      if I.find (' 192.168 ') > 0:        newlist.append (i)    newlist.sort ()    

I use NETSTAT-A instead of the program that needs to continue to output, the execution of the program, found that the program and the imagination is not the same, really real-time access to data, but the feeling is always a bit less harmonious, no matter, continue.

Step two, solve the problem of monitoring program

Program or dead, one of the key is to listen to the port, then just check the port on the line. Three ways:

1. Find the API for port detection

2. Connect the target port once, it's alive.

3. Netstat

The first method needs to find out whether there is no relevant API, the second method is easy to the normal operation of the target program caused problems, the third I do not want to use it. CMD redirection function is required here

# This method was used for Monitoringimport timeimport subprocessimport localeimport codecsdef getstdout (p):  mylist = [ ] While  True:    data = P.stdout.readline ()    if data = = B ":      if P.poll () is not None:        break    Else:
  mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name)  return mylistwhile True:  PS = subprocess. Popen (' Netstat-an | findstr "8080" ', stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=true)  resultlist = Getstdout (PS)  if Len (resultlist) >= 1:    pass  else:    print ( Time.strftime ("%y-%m-%d%h:%m:%s"))    subprocess. Popen (' taskkill.exe/f/im node.exe ', shell=false) # to prevent the action too fast, the new program was killed    Time.sleep (3)    subprocess. Popen (' Start node d:\\app.js ', shell=true)  

Netstat-an get the current port listening situation, "|" Redirect the output of Netstat to the FINDSTR function

Netstat-an | findstr "8080" to find the address line with 8080 ports, there is a description alive, otherwise it is hung.

The final step, integration

# This method was used for Monitoringimport timeimport subprocessimport localeimport codecsdef getstdout (p): MyList = [] While true:data = P.stdout.readline () if data = = B ": If P.poll () is not none:break Else:myli St.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name) return Mylistwhile True:ps = subprocess. Popen (' Netstat-an | findstr "8080" ', stdin=subprocess. PIPE, Stdout=subprocess.  PIPE, shell=true) resultlist = Getstdout (PS) If Len (resultlist) >= 1:pass else:print (Time.strftime ("%y-%m-%d %h:%m:%s ")) subprocess. Popen (' taskkill.exe/f/im node.exe ', Shell=false) time.sleep (3) PSS = subprocess. Popen (' Start cmd.exe/k node App.js ', stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=true) alist = Getstdout (PSS) NewList = [] for i in Alist:if i.find (' 192.168 ') > 0:ne  Wlist.append (i) Newlist.sort () print (' Sum of requests from LAN: ', Len (newlist)) Time.sleep (10)

Then found that there is a problem, the program will not be timed detection, will only be stuck on the ReadLine ().

Looking for a variety of problems, found that process.stdout.readline () is a synchronous method, no results will not return. Is there a way to be asynchronous?

Some people use fnctl,windows not support, pass

Asyncio? See for a long while not quite understand ...

Toss for a while, the last minute I still use C # to solve this problem ....

Reference code see http://www.jiamaocode.com/Cts/1031.html, can't open the words http://www.cnblogs.com/sode/archive/2012/07/10/2583941.html have reproduced

Finally solved the problem, but my heart is still uncomfortable, thinking for a long time how to solve the problem of asynchronous ReadLine (). Suddenly remembered to multi-threaded this weapon, simply open

A thread, does not return to wait, does not solve the problem.

# This method was used for Monitoringimport timeimport subprocessimport localeimport codecsimport threadingalist = []def ge      Tstdout (P, asy): If Asy:alist.clear () MyList = [] While true:data = P.stdout.readline () if data = = B ': If P.poll () is not none:break else:if asy:alist.append (Data.decode (Codecs.lookup (Locale.getprefe Rredencoding ()). Else:mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name)) re Turn Mylistwhile True:ps = subprocess. Popen (' netstat-an | findstr ' "', stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=true) resultlist = Getstdout (PS, False) If Len (resultlist) >=: NewList = [] for i in ALIST:I     F i.find ('. ') >: Newlist.append (i) Newlist.sort () print (' Sum of requests from LAN: ', Len (newlist)) Else: Print (Time.strftime ("%y-%m-%d%h:%m:%s")) subprocess. Popen (' taskkill.exe/f/im node.exe ', Shell=false) time.sleep () pss = subprocess. Popen (' Start cmd.exe/k node App.js ', stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=true) th = Threading.  Thread (Target=getstdout, ARGS=[PSS, True]) Th.start () Time.sleep ()

Summarize

Sometimes the simple solution can also achieve the same function, compared to the implementation of Python and C # implementation, C # more event-oriented, Python should also have a good solution, continue to explore ...

The above is a small part of the python to share the real-time access to CMD output of the relevant knowledge, I hope you like.

  • 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.