我需要在命令行中捕获错误,但不想在屏幕上打印错误消息。当出现错误时,我需要执行另一个命令。 下面是我的当前做法: hyst_cmd = "si viewhistory ..." process = subprocess.Popen(hyst_cmd, stdout=subprocess.PIPE) hyst = process.stdout.read().splitlines() 当我在某些项目中执行此操作时,屏幕上会显示错误消息。 对不起我的英语不好!
根据官方文档,subprocess中最常见的异常是OSError。为了捕获该错误,你可以尝试以下简单的方法:hyst_cmd = "si viewhistory ..." try: process = subprocess.Popen(hyst_cmd, stdout=subprocess.PIPE) hyst = process.stdout.read().splitlines() except OSError: <write_log_file or other action.> 如需更多信息,请查看下面的链接: 子进程异常
try-except
块中吗?这是捕获异常的好方法,而且你可以在except
块中指定另一个要运行的“命令”。 - shaktimaan