首页 > 解决方案 > 如何在 python shell 脚本中使用最后执行的命令的返回码

问题描述

美元问号 ($?) 用于查找最后执行的命令的返回值,我想在我的脚本中使用它,但它不起作用。

python 版本:3.7 库:子进程

我搜索了答案,但在 python 中找不到适合的答案。

我尝试了以下代码,但它不起作用:

#!/usr/bin/python
import subprocess
subprocess.call(["ls","-l"])
if $? == 0 :
    print("is ok\n")       

标签: pythonpython-3.xshell

解决方案


subprocess.call将返回代码,您可以将其存储在变量中:

import subprocess
rv = subprocess.call(["ls","-l"])  # <-- result of the call is stored inside `rv` variable
if rv == 0 :                       # <-- check the variable
  print("is ok")                   # <-- no need to put additional '\n' to print statement

印刷:

... the result of `ls -l`
is ok

推荐阅读