并行写入两个文件python

时间:2016-09-15 13:23:21

标签: python python-2.7

我只是试图在线程的帮助下并行写入两个文件。

def dmesg (i):

    cmd = 'dmesg'
    print cmd
    (status, cmd_out) = commands.getstatusoutput(cmd)
    fil = open('dmesg_logs', 'w')
    fil.write(cmd_out)
    fil.close()

def dump (i):

    cmd = 'lsmod'
    print cmd
    (status, cmd_out) = commands.getstatusoutput(cmd)
    fil = open('logs', 'w')
    fil.write(cmd_out)
    fil.close()
if __name__ == "__main__":

    t1 = threading.Thread(target = dmesg, args=(0,))
    t1.start()
    t2 = threading.Thread(target = dump, args=(0,))
    t2.start()
    while True : 
        "My own code"

这里我的问题是在线程2中没有创建日志文件。我能知道出错了吗?

1 个答案:

答案 0 :(得分:0)

cmd = ['dmesg']
with open ('dmesg_log.txt', 'w') as out1:
    retun1 = subprocess.Popen(cmd, shell = True, stdout=out1)

找到解决方案。以上代码适合我。