gpt4 book ai didi

Python 子进程在 stderr 中显示输出

转载 作者:行者123 更新时间:2023-12-01 09:31:13 26 4
gpt4 key购买 nike

我创建了以下脚本来在 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 中?我的脚本有错误吗?

最佳答案

你的代码看起来是正确的; shutdown 命令似乎将其输出发送到 stderr:

$ 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

关于Python 子进程在 stderr 中显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com