Python:在不同文件上打印每个线程的输出

时间:2017-08-21 12:38:42

标签: 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中执行此操作的解决方案。在此先感谢

2 个答案:

答案 0 :(得分: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();
    
  2. 保存模块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
    

答案 1 :(得分:0)

print调用不是线程安全的,因此您可以使用logging模块并为每个线程注册FileHandler,或使用多处理而不是线程,描述{{ 3}}