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 中做到这一点。提前致谢

使用记录器进行日志记录或写入文件

  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

print调用不是线程安全的,因此您可以使用logging模块并为每个线程注册一个FileHandler,也可以使用多处理而不是线程处理,如此处所述。

最新更新