【问题标题】:python write VLC log file (terminal return) using subprocess.Popenpython 使用 subprocess.Popen 写入 VLC 日志文件(终端返回)
【发布时间】:2014-08-19 06:58:21
【问题描述】:

我正在尝试将终端返回的结果写入一个名为 debug.log 的文件中。 我还想让 pid 终止进程,因为此时 kill 正在工作。 但是 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)

事实上,我想混合使用这两个示例。 谢谢

【问题讨论】:

  • 另外,f.close() 是多余的,因为 'with' 关键字会自动为您关闭文件。
  • 啊好吧,我不知道!
  • 是的,我试过了,但文件总是空的......我正在尝试用你的回复做不同的事情
  • 试图适应这个response,但对我来说并不容易!
  • 我已经编辑了我的问题,希望对你有所帮助

标签: python logging subprocess vlc


【解决方案1】:

您需要将“stderr”(不是“stdout”)重定向到“out”。

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

【讨论】:

  • 感谢您的回复,但还是一样。 with open("/home/user/.cache/debug.log", 'w') as subprocess.PIPE: proc = subprocess.Popen(cmd1, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)文件也是空的
  • @Guillaume - 我也添加了访问输出字符串的代码。
  • @Guillaume - 我提供的代码适用于我系统上的测试用例,但是,我无法复制你的。我不确定你现在得到什么样的终端输出,以及你需要什么。阅读子流程文档,看看是否有帮助 - docs.python.org/2/library/subprocess.html
  • 我觉得vlc的返回不一样,要加"preexec_fn=os.setsid" 杀掉进程。但我真的不知道这是什么
猜你喜欢
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
  • 2021-03-27
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多