Run subprocess and print output to logging

后端 未结 3 374
甜味超标
甜味超标 2020-12-02 17:10

I am looking for the way to call shell scripts from python and write their stdout and stderr to file using logging. Here is my code:



        
3条回答
  •  自闭症患者
    2020-12-02 17:17

    You could try to pass the pipe directly without buffering the whole subprocess output in memory:

    from subprocess import Popen, PIPE, STDOUT
    
    process = Popen(command_line_args, stdout=PIPE, stderr=STDOUT)
    with process.stdout:
        log_subprocess_output(process.stdout)
    exitcode = process.wait() # 0 means success
    

    where log_subprocess_output() could look like:

    def log_subprocess_output(pipe):
        for line in iter(pipe.readline, b''): # b'\n'-separated lines
            logging.info('got line from subprocess: %r', line)
    

提交回复
热议问题