Get cmd output in real time using Python

Source: Internet
Author: User
Tags locale

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 TimeImportsubprocessImportlocaleImportcodecsmylist=[]ps= subprocess. Popen ('netstat-a', Stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=True) whileTrue:data=Ps.stdout.readline ()ifdata = = B"':        ifPs.poll () is  notNone: Break    Else: Mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name) NewList= []         forIinchMyList:ifI.find ('192.168') >0:newlist.append (i) newlist.sort ()Print('Sum of requests from LAN:', Len (newlist))

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 TimeImportsubprocessImportlocaleImportCodecsdefgetstdout (P): MyList= []     whileTrue:data=P.stdout.readline ()ifdata = = B"':            ifP.poll () is  notNone: Break        Else: Mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name))returnMyList whileTrue:ps= subprocess. Popen ('Netstat-an | findstr "8080"', Stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=True) Resultlist=Getstdout (PS)ifLen (resultlist) >= 1:        Pass    Else:        Print(Time.strftime ("%y-%m-%d%h:%m:%s") ) subprocess. Popen ('taskkill.exe/f/im Node.exe', shell=False)
# Prevent the action too fast, the new program is Dead Time.sleep (3) subprocess. Popen ('Start node D:\\app.js', shell=True) Time.sleep (10)

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 TimeImportsubprocessImportlocaleImportCodecsdefgetstdout (P): MyList= []     whileTrue:data=P.stdout.readline ()ifdata = = B"':            ifP.poll () is  notNone: Break        Else: Mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name))returnMyList whileTrue:ps= subprocess. Popen ('Netstat-an | findstr "8080"', Stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=True) Resultlist=Getstdout (PS)ifLen (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= []         forIinchalist:ifI.find ('192.168') >0:newlist.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, do not return to wait, do not solve the problem.

#This method was used for monitoringImport TimeImportsubprocessImportlocaleImportCodecsImportthreadingalist= []defgetstdout (P, asy):ifasy:alist.clear () mylist= []     whileTrue:data=P.stdout.readline ()ifdata = = B"':            ifP.poll () is  notNone: Break        Else:            ifasy:alist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name))Else: Mylist.append (Data.decode (Codecs.lookup (locale.getpreferredencoding ()). Name))returnMyList whileTrue:ps= subprocess. Popen ('Netstat-an | findstr "8080"', Stdin=subprocess. PIPE, Stdout=subprocess. PIPE, shell=True) Resultlist=Getstdout (PS, False)ifLen (resultlist) >= 1: NewList= []         forIinchalist:ifI.find ('192.168') >0: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 (3) 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 (10)
View Code

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

P.S. Note that the cmd output in the Unicode system is B ' of this type of string, transcoding is not clearly recommended for the default encoding of your system with Codecs.lookup (Locale.getpreferredencoding ()). Name, Rushed to use utf-8 various pits.

Get cmd output in real time using Python

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.