![](/img/trans.png)
[英]How to run tcpdump with 2 parameters in as subprocess in python and how to get its output?
[英]How to get subprocess output during its running?
我有2个文件main.py和infinit.py,如下所示:
main.py
#!/usr/bin/python
import logging
import subprocess
import sys
logging.basicConfig(level=logging.INFO)
def forever():
cmd = [sys.executable, 'infinit.py']
while 1:
try:
print 'running new instance of:'
print ' '.join(cmd)
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True)
for line in iter(popen.stderr.readline, ""):
print line,
for line in iter(popen.stdout.readline, ""):
print line,
except Exception as e:
print 'Something bad happend'
logging.error(e)
if __name__ == '__main__':
forever()
无穷大
#!/usr/bin/python
import logging
logging.basicConfig(level=logging.INFO)
i = 0
while 1:
i += 1
logging.info('i: {0}'.format(i))
print i
我运行main.py,我想在控制台中同时看到(打印和日志记录)。 我也希望它在Windows和Linux上运行。 另外,它是否可以在Windows空闲状态下工作(打印和记录)?
在程序开始时添加此行,并输入相同的LOG_FILENAME,然后可以使用tail -f unix命令查看输出。
import logging
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG, filemode = 'w+')
logging.getLogger().setLevel(logging.DEBUG)
我发现了两个解决方案,它们都可以在Linux和Windows甚至Windows Idle上运行:
在父进程中,打印子进程的stderr:
#!/usr/bin/python
import logging
import subprocess
import sys
def forever():
cmd = [sys.executable, 'infinit.py']
while 1:
try:
print 'running new instance of:'
print ' '.join(cmd)
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True)
for line in iter(popen.stderr.readline, ""):
print line,
except Exception as e:
print 'Something bad happend'
logging.error(e)
if __name__ == '__main__':
forever()
目前:
无穷大
#!/usr/bin/python
import logging
import sys
import time
logging.basicConfig(level=logging.INFO)
sys.stdout = sys.stderr
i = 0
while 1:
i += 1
logging.info('i: {0}'.format(i))
print i
time.sleep(0.2)
我的代码适应了解决方案
main.py
#!/usr/bin/python
import logging
import subprocess
import sys
def forever():
CMD = [sys.executable, 'infinit.py']
while 1:
try:
print 'running new instance of:'
print ' '.join(CMD)
popen = subprocess.Popen(CMD, stdout=subprocess.PIPE)
for line in iter(popen.stdout.readline, ""):
print line,
except Exception as e:
print 'Something bad happend'
logging.error(e)
finally:
print
if __name__ == '__main__':
forever()
inifinit.py
#!/usr/bin/python
import logging
import sys
import time
class FlushFile(object):
"""Write-only flushing wrapper for file-type objects."""
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
logging.basicConfig(level=logging.INFO)
sys.stdout = FlushFile(sys.stdout)
i = 0
while 1:
i += 1
logging.info('i: {0}'.format(i))
print i
time.sleep(0.2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.