Python:脚本输出损坏

时间:2017-12-04 13:51:22

标签: python multithreading stdout

我有以下Python脚本,用于ping命令行上传递的IP列表。

#! /usr/bin/python

import sys, time
from threading import Thread
import subprocess
from Queue import Queue
num_threads = 255
queue = Queue()
p=0
f=0
t=0

def timestamp():
    lt = time.localtime(time.time())
    return "%02d.%02d.%04d %02d:%02d:%02d" % (lt[2], lt[1], lt[0], lt[3], lt[4], lt[5])

def pinger(i, q):
    global p
    global f

    while True:
        ip = q.get()
        ret = subprocess.call("ping -c 2 %s" % ip,
                        shell=True,
                        stdout=open('/dev/null', 'w'),
                        stderr=subprocess.STDOUT)
        if ret == 0:
            print(ip+"\tpassed")
            time.sleep(0.1)
            p+=1
        else:
            print(ip+"\tfailed")
            time.sleep(0.1)
            f+=1
        q.task_done()

for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()

print("\nStarted at "+timestamp())

for ip in open(sys.argv[1]).readlines():
    ip=ip.strip()
    queue.put(ip)
    t+=1

queue.join()
print(str(t) + " IPs pinged, " + str(p) + " passed, " + str(f) + " failed\n")
print("\nFinished at "+timestamp())

在大多数情况下,输出就像这样完美,标签分离为Excel

192.168.188.1   failed
192.168.199.107 passed
192.168.7.2     passed
192.168.199.108 failed

但每次,随机,我都会遇到输出问题,例如一行上的奇数缩进

192.168.164.173 failed
 192.168.164.190        failed

或者一个字段中的奇数缩进 - 这里的IP是缩进的但不是消息

 172.29.19.132  failed

或连接后跟一个空行

172.29.9.37     passed172.29.19.133     passed

172.29.9.39     passed

这些组合并不总是相同的IP。 我已经确保ip列表是干净的,并尝试减少线程数,引入打印延迟,并刷新STDOUT无济于事。有什么想法吗?

0 个答案:

没有答案