Python subprocess输出显示在stderr问题求助(附Ubuntu定时关机脚本)
嘿,我来帮你搞定这个subprocess输出跑到stderr的问题!
首先得说清楚:这不是你的代码写错了,而是很多Linux系统命令(比如shutdown)的设计就是把正常的状态提示信息输出到stderr,而非stdout。比如你执行shutdown -h +10时,终端里看到的“系统将在10分钟后关闭”这类提示,其实是命令往stderr里打的内容,而不是真正的错误。
下面给你两个实用的解决方案:
方案1:合并stdout和stderr,统一捕获所有输出
如果你不想区分标准输出和错误输出,只想把所有内容都当成命令的输出捕获,可以在调用subprocess.run()时加上stderr=subprocess.STDOUT参数,让stderr的内容直接合并到stdout中:
import subprocess def execute_command(command): command = command.split() try: print(f"Running command: {' '.join(command)}") # 核心修改:把stderr合并到stdout,同时用text=True自动解码成字符串 command_process = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) print(f"Command output:\n{command_process.stdout}") # 检查命令是否执行成功 if command_process.returncode != 0: print(f"⚠️ Command failed with return code {command_process.returncode}") except Exception as e: print(f"❌ Unexpected error when running command: {str(e)}") # 测试:设置10分钟后关机 execute_command("shutdown -h +10")
方案2:区分处理,但把成功时的stderr当成正常提示
如果你需要明确区分标准输出和错误输出,但又不想把关机的正常提示当成错误,可以通过命令的返回码来判断:返回码为0时,stderr里的内容是正常状态提示;返回码非0时,才是真正的错误:
import subprocess def execute_command(command): command = command.split() try: print(f"Running command: {' '.join(command)}") command_process = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # 打印标准输出(如果有的话) if command_process.stdout: print(f"📋 Command stdout:\n{command_process.stdout}") # 处理stderr:根据返回码判断是提示还是错误 if command_process.stderr: if command_process.returncode == 0: print(f"ℹ️ Command status message:\n{command_process.stderr}") else: print(f"❌ Command error:\n{command_process.stderr}") # 最终检查返回码 if command_process.returncode != 0: print(f"⚠️ Command exited with code {command_process.returncode}") except Exception as e: print(f"❌ Unexpected error: {str(e)}") execute_command("shutdown -h +10")
另外补充个小细节:如果你的脚本没有用sudo运行,shutdown会直接报错,这时候stderr里就是真正的权限错误,上面的代码也能正确识别并提示你。
内容的提问来源于stack exchange,提问作者arshovon
相关产品推荐
相关产品推荐

