python使用subprocess.Popen编写VLC日志文件(终端返回)

时间:2014-06-28 06:03:30

标签: python logging subprocess vlc

我试图在名为 debug.log 的文件中写入终端的返回。 我也想让pid杀死这个过程,因为这一刻杀人正在发挥作用。 但是debug.log是空的

cmd1 = "cvlc rtp://232.0.2.183:8200 --sout file/mkv:/media/file.mkv"
with open("/home/user/.cache/debug.log", 'w') as out:
    proc = subprocess.Popen(cmd1, stdout=out, shell=True, preexec_fn=os.setsid)
pid = proc.pid
with open("/home/user/.cache/pid.log", 'w') as f:
    f.write(str(pid))
f.close()

编辑:我正在使用此method来终止该进程 和这个方法(来自here)写日志:

    ###########kill the process############
    import os
    import signal
    import subprocess

    # The os.setsid() is passed in the argument preexec_fn so
    # it's run after the fork() and before  exec() to run the shell.
    pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                           shell=True, preexec_fn=os.setsid) 

    os.killpg(pro.pid, signal.SIGTERM)  # Send the signal to all the process groups    

    ######### write the log #############
    import subprocess

    cmd = ['ls', '-l']       # example of command
    with open('output.txt', 'w') as out:
        return_code = subprocess.call(cmd, stdout=out)

事实上,我想混合两个例子。 感谢

1 个答案:

答案 0 :(得分:1)

你需要将'stderr'(不是'stdout')重定向到'out'。

proc = subprocess.Popen(cmd1, stderr=out, shell=True, preexec_fn=os.setsid)