我需要从python脚本运行shell命令。我正在使用库子进程。我想将此命令打包成try / except块,以防出现某些错误。但是,我无法从result
块中的变量except
中获取信息,该变量已写在try
中。我试图从try / except块中声明结果对象,但是找不到有效的解决方案。这是我的代码
import subprocess
result = None
try:
result = subprocess.run(['lsdkdfk'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout)
except Exception as e:
print(result.stderr) #this doesn't work
有人可以帮我吗?
subprocess.run
抛出FileNotFoundError,如果找不到您要使用的命令,则不会返回任何内容。 “ lsdkdfk”不是有效命令,因此result
从未分配任何内容,也没有stderr可供查看。但是,您可以根据需要打印捕获的异常。
如果找到命令但命令本身失败,除非您指定参数check=True
,否则它不会引发异常。现在您还可以查看标准错误。
>>> try:
... result = subprocess.run(["ls", "asdf"], capture_output=True, encoding="utf-8")
... except FileNotFoundError as e:
... print("I caught this: ", e)
...
>>> result.stdout
''
>>> result.stderr
"ls: cannot access 'asdf': No such file or directory\n"
>>> try:
... result = subprocess.run(["invalidcmd", "asdf"], capture_output=True, encoding="utf-8")
... except FileNotFoundError as e:
... print("I caught this: ", e)
...
I caught this: [Errno 2] No such file or directory: 'invalidcmd'