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

前端 未结 6 1749
轮回少年
轮回少年 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:20

    You may write the stdout/err to a file after the command execution. In the example below I use pickling so I am sure I will be able to read without any particular parsing to differentiate between the stdout/err and at some point I could dumo the exitcode and the command itself.

    import subprocess
    import cPickle
    
    command = 'ls -altrh'
    outfile = 'log.errout'
    pipe = subprocess.Popen(command, stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE, shell = True)
    stdout, stderr = pipe.communicate()
    
    f = open(outfile, 'w')
    cPickle.dump({'out': stdout, 'err': stderr},f)
    f.close()
    

提交回复
热议问题