如何检查命令是否成功?

How can I check if a command was succesful or not?

所以,我正在尝试在执行子进程命令时检查命令是否成功。

我真的不擅长解释,但请看我的例子:

这是我的代码

output = subprocess.getoutput("sdf")
print(output)

我想检查输出是否是:

'sdf' is not recognized as an internal or external command,
operable program or batch file.

我试过这段代码:

error_temp = fr"'sdf' is not recognized as an internal or external command, operable program or batch file."
if output == error_temp:
   print("'sdf' was not recognized by this system, please register this command and try again later.")
else:
   print(output)

但这并没有真正起作用,我认为这与输出中的跳行有关...

感谢任何帮助,谢谢。

编辑:

感谢@Cristian

,我解决了这个问题

这是我更新后的代码:

status = subprocess.getstatusoutput("sdf")
print(status[0])

您可以使用同一包中的 getstatusoutput 函数。它 returns 一个带有退出代码和消息的元组。如果退出代码为 0,则视为成功完成。其他代码表示异常完成。

我只想展示 getstatusoutput 的替代方法,这是一种总是启动 shell 来执行您的程序的旧方法,如果您不需要 shell 的功能,这可能效率低下=43=]提供(如通配符扩展)。

以下使用subprocess.run(如果您指定shell=True,也可以使用shell来执行您的程序)。第一个示例不捕获已执行程序的输出,而第二个示例捕获。 运行 的程序是一个小的 Python 程序,test.py,使用命令 python test.py

执行

test.py

print('It works.\n')

示例 1 -- 不捕获输出

import subprocess


completed_process = subprocess.run(['python', 'test.py'])
print(completed_process.returncode)

打印:

It works.
0

示例 2 -- 捕获输出

import subprocess


completed_process = subprocess.run(['python', 'test.py'], capture_output=True, text=True)
print(completed_process.returncode)
print(completed_process.stdout)

打印:

0
It works.