# this method is used for monitoring
import time
import subprocess
import locale
import codecs
def 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 mylist
while 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:
newlist.append(i)
newlist.sort()
print('Sum of requests from LAN:', len(newlist))
time.sleep(10)
然后发现有问题,程序完全不会定时检测,只会卡在readline()上。
各种找问题,发现那个process.stdout.readline()是个同步方法,没结果就不返回。有没有的能异步的方法?
有人用fnctl,windows不支持,pass
asyncio?看了半天没太明白...
折腾了半天,最后关头我还是用c#解决这个问题了....
参考代码见http://www.jiamaocode.com/Cts/1031.html,打不开的话http://www.cnblogs.com/sode/archive/2012/07/10/2583941.html有转载
总算解决了这个问题,但是我心中还是不爽,思考了很久如何解决异步readline()的问题。忽然想起来多线程这个利器,干脆开
一个线程,不返回就等着,不就问题解决了。
# this method is used for monitoring
import time
import subprocess
import locale
import codecs
import threading
alist = []
def getstdout(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.getpreferredencoding()).name))
else:
mylist.append(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
return mylist
while 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:
if 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()
总结
有时候简单的解决方法也可以实现同样的功能,对比python的实现与C#的实现,C#更面向事件一点,python应该也有不错的解决方案,继续摸索...
以上内容是小编给大家分享的Python实时获取cmd的输出的相关知识,希望大家喜欢。
本文原创发布php中文网,转载请注明出处,感谢您的尊重!
相关文章
相关视频