使用subprocess.Popen在Python中写入VLC日志文件(终端返回)

0 投票
1 回答
584 浏览
提问于 2025-04-18 11:24

我想把终端的输出写入一个叫做 debug.log 的文件里。同时,我也想获取进程的ID,以便可以结束这个进程,目前结束进程的功能是可以用的。但问题是,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()

补充一下:我正在使用这个 方法 来结束进程,另外我用这个方法(来自 这里)来写日志:

    ###########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 个回答

1

你需要把'错误输出'(不是'正常输出')重定向到'输出'。

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

撰写回答