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

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

    I suggest you write your own handlers, something like (not tested, I hope you catch the idea):

    class my_buffer(object):
        def __init__(self, fileobject, prefix):
            self._fileobject = fileobject
            self.prefix = prefix
        def write(self, text):
            return self._fileobject.write('%s %s' % (self.prefix, text))
        # delegate other methods to fileobject if necessary
    
    log_file = open('log.log', 'w')
    my_out = my_buffer(log_file, 'OK:')
    my_err = my_buffer(log_file, '!!!ERROR:')
    p = subprocess.Popen(command, stdout=my_out, stderr=my_err, shell=True)
    

提交回复
热议问题