2016-11-15 10 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() 

このコードは(出力にスレッドIDが含まれます)-dオプションを私に返します。

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 

最初の質問は次のとおりです。 すべてのスレッドは、各スレッドの使用の1ので、1行にプリントアウト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 

2番目の質問は次のとおりです。 出力から空行を削除する方法?

答えて

0

あなたはsys.stdoutで正しいトラックにいます。両方の問題への単純なsolutinこの

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

のような関数であっても、代わりにsys.stdout

+0

はありがとう、それを使用します。私はPythonの新機能です。それは通常の解決法か、結果を達成するための他の方法ですか? –

+0

@MikhailTokarev私は通常、スレッドセーフなので、組み込みのロギングモジュールです。迅速な解決策のために、これはうまく動作します。 –

+0

ありがとうアレックス –