Merging a Python script's subprocess' stdout and stderr while keeping them distinguishable

前端 未结 6 1734
轮回少年
轮回少年 2020-12-04 14:44

I would like to direct a python script\'s subprocess\' stdout and stdin into the same file. What I don\'t know is how to make the lines from the two sources distinguishable?

6条回答
  •  北海茫月
    2020-12-04 15:10

    tsk = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    

    subprocess.STDOUT is a special flag that tells subprocess to route all stderr output to stdout, thus combining your two streams.

    btw, select doesn't have a poll() in windows. subprocess only uses the file handle number, and doesn't call your file output object's write method.

    to capture the output, do something like:

    logfile = open(logfilename, 'w')
    
    while tsk.poll() is None:
        line = tsk.stdout.readline()
        logfile.write(line)
    

提交回复
热议问题