Get the output of cmd in real time using Python
Reprinted from: http://www.ifindbug.com/doc/id-44974/name-Get the output of cmd in real time using Python.html
Recently, I found a problem. The console program written by a guy is not robust enough. When monitoring SOCKET, it is easy to crash, causing the program to crash as a whole. Unfortunately, he has not found a solution to the problem and has been unable to solve it, but this is another monitoring program. It is still more important, and we must find a way to solve it.
(This is going to kill my rhythm....) Since I don't know the language he uses, I can only think of ways outside the program.
1. When the target program is executed, it will monitor port 8080, TCP, and output the client's IP address through the console after each client connection.
2. The monitoring is not done at one time, but is always monitored, and the program will not exit
3. In order to monitor the needs, it is best to sort and organize the connected IPs.
The PS system is based on the windows platform.
I thought of doing a monitoring program, it is better to be simple, so I thought of Python.
My expected logic is as follows. Use python to detect whether the target program has crashed. If the bid is won, the target program will be started and monitored. After each output, python will perform a data operation and then loop.
I used netstat -a to replace the program that needs continuous output, execute the program, and found that the program is different from what I imagined. It is indeed real-time to obtain data, but it always feels a little discordant, no matter, continue.
The program may still be dead, and a very critical point is to monitor the port, so just check the port. Three ways:
1. Find the API for port detection
2. Connect to the target port once, and it will be alive if it is connected
The first method needs to find out if there is any related API, the second method is easy to cause problems to the normal operation of the target program, and the third method is used without even thinking about it. Here you need to use the redirection function of cmd
netstat -an gets the current port listening status, "|" redirects the output of netstat to the findstr function
netstat -an | findstr "8080" Find the address line with port 8080, if there is, it means it is alive, otherwise it is hung up.