Python 子进程正在 stderr 中显示输出
Python subprocess is showing output in stderr
我创建了以下脚本以在 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
命令似乎将其输出发送到标准错误:
$ 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
我创建了以下脚本以在 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
命令似乎将其输出发送到标准错误:
$ 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