Python子进程正在stderr中显示输出
我创建了以下脚本,在X分钟后关闭Ubuntu机器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,
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
是一个特殊的文件,它会丢弃所有写入它的内容)。非常感谢。我为未来的读者更新了答案。