Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python子进程正在stderr中显示输出_Python_Ubuntu_Terminal_Python 3.5 - Fatal编程技术网

Python子进程正在stderr中显示输出

Python子进程正在stderr中显示输出,python,ubuntu,terminal,python-3.5,Python,Ubuntu,Terminal,Python 3.5,我创建了以下脚本,在X分钟后关闭Ubuntu机器 import subprocess def execute_command(command): command = command.split() try: print(command) command_process = subprocess.run(command, stdout=subprocess.PIPE,

我创建了以下脚本,在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.
我的问题是:

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

  • 您的代码似乎正确;
    shutdown
    命令将其输出发送到stderr:

    $ shutdown +9 >/dev/null
    Shutdown scheduled for Sat 2018-04-21 15:38:00 BST, use 'shutdown -c' to cancel.
    
    shutdown+92>/dev/null
    不产生任何输出

    说明:

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

    参考资料:

    这真是一种解脱!你能在回答中添加关于
    /dev/null
    2>/dev/null
    的解释吗?关于这一点,我将让你参考(简而言之,
    将stdout重定向到一个文件,而
    2>
    将stderr重定向到一个文件;
    /dev/null
    是一个特殊的文件,它会丢弃所有写入它的内容)。非常感谢。我为未来的读者更新了答案。