python实时获取cmd输出保存_Python实时获取cmd的输出

# 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中文网,转载请注明出处,感谢您的尊重!

相关文章

相关视频

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值