2017-08-21 27 views
1

各スレッドの出力を異なるファイルに出力したい。 これは私のコードは、スレッドのためである: -Python:各スレッドの出力を別のファイルに出力する

def __init__(self, command): 
     threading.Thread.__init__(self) 
     self.command = command 


def run(self): 
     call(self.command) 

def get_devices(): 

     command_res = 'adb devices' 
     results = os.popen(command_res, "r") 
     command_result = '' 
     while 1: 
      line = results.readline() 
      if not line: break 
      command_result += line 
     devices = command_result.partition('\n')[2].replace('n','').split('\tdevice') 
     return [device for device in devices if len(device) > 2] 

for device_id in device_ids : 
    threads.append(Universal([sys.argv[1], device_id])) 

for thread in threads: 
    try: 
     thread.start(); 
    except: 
     print("Error: unable to start thread") 

for thread in threads: 
    thread.join(); 

はここdevice_idsは、添付の私のデバイスのリストです。各デバイスは別々のスレッドで動作します。 Pythonでこれを行う方法はありますか?あなたがloggingモジュールを使用し、各スレッドのFileHandlerを登録、またはスレッドの代わりに、マルチプロセッシングを使用することができますいずれかのように、アドバンス

答えて

0

print呼び出しは、スレッドセーフではありませんおかげで、hereを説明しました。

1
ロギング用

使用ロガーまたは新しいファイルハンドラで新しいロガーを取得するための関数を作成します

  1. をファイルに書き込みます。それ保存

    import logging 
    from threading import Thread 
    import sys 
    import subprocess 
    
    device_ids = ["d1","d2","d3"] 
    threads = [] 
    def get_logger(name, log_file, level=logging.INFO): 
    
        handler = logging.FileHandler(log_file)   
        logger = logging.getLogger(name) 
        logger.setLevel(level) 
        logger.addHandler(handler) 
    
        return logger 
    
    
    class Universal(Thread): 
        def __init__(self, command,device_id,logger): 
         Thread.__init__(self) 
         self.command = command 
         self.logger = logger 
         self.logger.info("thread instance init" + str(device_id)) 
    
        def run(self): 
         self.logger.info("thread started" + str(device_id)) 
         subprocess.call(self.command) 
    
    
    for device_id in device_ids : 
        name = str(device_id) 
        f_name = str(device_id) + str(".log") 
        log = get_logger(name,f_name) 
        threads.append(Universal(sys.argv[1], device_id,log)) 
    
    for thread in threads: 
        try: 
         thread.start(); 
        except: 
         print("Error: unable to start thread") 
    
    for thread in threads: 
        thread.join(); 
    

でモジュールa.pyとコマンド

python a.py ls 

出力

Public Videos d1.log Desktop github Music Templates d2.log Doccuments gitlab Pictures d3.log Downloads torch 

Public Videos d1.log Desktop github Music Templates d2.log Doccuments gitlab Pictures d3.log Downloads torch 

Public Videos d1.log Desktop github Music Templates d2.log Doccuments gitlab Pictures d3.log Downloads torch 
+0

でそれを実行し、私は、このエラーはAttributeErrorを得る: '関数' オブジェクトが持っています属性 'info'なし –

+0

スクリプトを実行すると、引数として渡すべきは何ですか?後でスクリプトでデバイスIDを取得し、ログャーについてはどうすればいいですか? –

+0

@NehaAgarwalは私の更新された答えとその出力を確認します – Kallz

関連する問題