【问题标题】:python 3 multithreading output to CSV file (blank)python 3多线程输出到CSV文件(空白)
【发布时间】:2014-12-13 22:35:30
【问题描述】:

我是 python 新手,我从我遇到的一个教程中得到了这个多线程。 不确定这是否是好的做法。

我要存档的内容: ping 主机名列表并向上或向下返回。 将结果写入 csv 文件

这个文件目前的作用是: ping 主机名列表并向上或向下返回。 它创建的 csv 文件是空的,似乎没有向其中写入任何结果。

我做了一些测试,发现使用 pings 多线程在串行代码上对我来说快了大约 16 倍。 我正在执行大约 9000 的大量 ping,并希望它们尽快返回。

能否请您告诉我 csv 部分哪里出了问题。

import threading
from queue import Queue
import time
import subprocess as sp
import csv

# lock to serialize console output
lock = threading.Lock()

def do_work(item):
    #time.sleep(1) # pretend to do some lengthy work.
    # Make sure the whole print completes or threads can mix up output in one line.

    status,result = sp.getstatusoutput("ping -n 3 " + str(item))
    if status == 0:
        result = 'Up'
    else:
        result = 'Down'

    with lock:
        output.writerow({'hostname': item,'status': result})
        array.append({'hostname': item,'status': result})
        print(threading.current_thread().name,item,result)

# The worker thread pulls an item from the queue and processes it
def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

# Create the queue and thread pool.
q = Queue()
for i in range(100):
     t = threading.Thread(target=worker)
     t.daemon = True  # thread dies when main thread (only non-daemon thread) exits.
     t.start()

array = []
# stuff work items on the queue (in this case, just a number).
start = time.perf_counter()

headers = ['status','hostname']
output = csv.DictWriter(open('host-export.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)
output.writeheader()

txt = open("hosts.txt", 'r', encoding="utf8")
for line in txt:
    q.put(line,array)

q.join()       # block until all tasks are done

# "Work" took .1 seconds per task.
# 20 tasks serially would be 2 seconds.
# With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
print(array)

print('time:',time.perf_counter() - start)

我还为 csv 添加了批量写入,我想也许我只是无法访问函数中的 csv 对象,但这也没有像下面那样工作。

headers = ['status','hostname']
output = csv.DictWriter(open('host-export.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)
output.writeheader()
output.writerows(array)

【问题讨论】:

  • 脚本的输出是什么?
  • 目前它将结果打印到控制台,但我希望它也写入 csv,因为有 9000 个结果
  • 示例输出“Thread-16 wordpress.com UP”,分解方式是线程名称,然后是站点 i ping,然后是状态。我在这里 ping 的站点仅用于测试,这将用于我工作中的内部设备状态测试。

标签: multithreading csv python-3.x python-3.4 python-multithreading


【解决方案1】:

我弄清楚我做错了什么。 我没有关闭文件连接,所以它没有写入文件。

这是我现在用来定位我的 csv 文件的代码。

fieldnames = ['ip', 'dns', 'pings'] #headings 
test_file = open('test2-p.csv','w', newline='') #open file
csvwriter = csv.DictWriter(test_file, delimiter=',', fieldnames=fieldnames) #set csv writing settings
csvwriter.writeheader() #write csv headings 
for row in rows: #write to csv file
     csvwriter.writerow(row)
test_file.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多