【问题标题】:Python subprocess is showing output in stderrPython 子进程在 stderr 中显示输出
【发布时间】:2018-10-02 01:25:06
【问题描述】:

我创建了以下脚本以在 X 分钟后关闭 Ubuntu 机器。

import subprocess

def execute_command(command):
    command = command.split()
    try:
        print(command)
        command_process = subprocess.run(command,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
        output = command_process.stdout.decode('utf-8')            
        output_message = "Command output: {}".format(output)
        error = command_process.stderr.decode('utf-8')            
        error_message = "Command error: {}".format(error)
        print(output_message)
        print(error_message)
    except Exception as error:
        command_error = str(error)
        print("Error: "+command_error)

command = "shutdown -h 50"
execute_command(command)

输出:

['shutdown', '-h', '50']
Command output: 
Command error: Shutdown scheduled for Sat 2018-04-21 19:37:25 +06, use 'shutdown -c' to cancel.

我的问题:

  1. 为什么stdout 是空的?
  2. 为什么消息显示在stderr 中?我的脚本有错误吗?

【问题讨论】:

    标签: python ubuntu terminal python-3.5


    【解决方案1】:

    您的代码似乎正确; shutdown 命令似乎将其输出发送到标准错误:

    $ shutdown +9 >/dev/null
    Shutdown scheduled for Sat 2018-04-21 15:38:00 BST, use 'shutdown -c' to cancel.
    

    shutdown +9 2>/dev/null 不产生任何输出。

    解释:

    • >stdout 重定向到文件
    • 2>stderr 重定向到文件
    • /dev/null 是一个特殊文件,会丢弃所有写入其中的内容

    参考:TLDP

    【讨论】:

    • 这很缓解!您能否在答案中添加有关>/dev/null2>/dev/null 的解释?
    • 为此,我将向您推荐TLDP(简而言之,> 将 stdout 重定向到文件,2> 将 stderr 重定向到文件;/dev/null 是一个特殊的文件,丢弃所有写入它的东西)。
    • 非常感谢。我为未来的读者更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2012-10-04
    • 2011-12-05
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    相关资源
    最近更新 更多