2016-11-15 27 views
0

我想完成關於線程模塊的練習。在我的例子中,我只想創建只打印文件名的工作人員。線程與隊列,並在Python中同時打印

import optparse 
import os 
import queue 
import threading 

def main(): 
    opts, args = parse_options() 
    filelist = get_files(args) 
    worker_queue= queue.Queue() 

for i in range(opts.count): 
    threadnum  = "{0}: ".format(i+1) if opts.debug else "" 
    worker   = Worker(worker_queue, threadnum) 
    worker.daemon = True 
    worker.start() 
for file in filelist: 
    worker_queue.put(file) 
worker_queue.join() 

class Worker(threading.Thread): 


    def __init__(self, worker_queue, threadnum): 
     super().__init__() 
     self.worker_queue = worker_queue 
     self.threadnum  = threadnum 
     self.result   = [] 

    def run(self): 
     while True: 
      try: 
       file = self.worker_queue.get() 
       self.process(file) 
      finally: 
       self.worker_queue.task_done() 

    def process(self, file): 
     print("{0}{1}".format(self.threadnum, file)) 

def parse_options(): 

    parser  = optparse.OptionParser(
    usage  = "xmlsummary.py [options] [path] outputs a summary of the XML files in path; path defaults to .") 
    parser.add_option("-t", "--threads", dest = "count", default = 7,type = "int", help = ("the number of threads to use (1..20) [default %default]")) 
    parser.add_option("-v", "--verbose", default = False, action = "store_true", help = ("show verbose information if requested, [default %default]")) 
    parser.add_option("-d", "--debug", dest = "debug", default = False, action = "store_true", help = ("show debug information such as thread id, [default, %default]")) 
    opts, args = parser.parse_args() 

    if not (1 <= opts.count <= 20): 
     parser.error("threads must be in following range (1..20)") 

return opts, args 

def get_files(args): 
    filelist = [] 
    for item in args: 
    if os.path.isfile(item): 
     filelist.append(item) 
    else: 
     for root, dirs , files in os.walk(item): 
      for file in files: 
       filelist.append(os.path.join(root, file)) 
    return filelist 
main() 

此代碼返回我-d選項(其中將包括在輸出線程ID):

1: C:\P\1.jpg2: C:\P\2.jpg3: C:\P\3chapter.bat4: C:\P\423.txt5: C:\P\a.txt6: C:\P\bike.dat7: C:\P\binary1.dat 

的第一個問題是: 所有線程在同一行打印出來,因爲每個線程使用一個sys.stdout

我有以下改變打印命令:

def process(self, file): 
print("{0}{1}\n".format(self.threadnum, file)) 

現在這個我有以下結果:

1: C:\P\1.jpg 
2: C:\P\2.jpg 
3: C:\P\3chapter.bat 
4: C:\P\423.txt 
5: C:\P\a.txt 
6: C:\P\bike.dat 
7: C:\P\binary1.dat 







1: C:\P\dckm.txt 
2: C:\P\dlkcm.txt 
3: C:\P\email.html 

第二個問題是: 如何從輸出中刪除空行?

回答

0

你在正確的軌道上,sys.stdout。一個簡單的solutin這兩個問題會是這樣

def tprint(msg): 
    sys.stdout.write(str(msg) + '\n') 
    sys.stdout.flush() 

的函數,用它來代替sys.stdout

+0

謝謝。我是Python新手。這是正常的解決方案還是其他方式來達到結果? –

+0

@MikhailTokarev我通常會使用的是內置日誌記錄模塊,因爲它是線程安全的。對於快速解決方案,這工作正常。 –

+0

謝謝亞歷克斯 –