python - 如何在 python shell 脚本中使用最后执行的命令的返回码
问题描述
美元问号 ($?) 用于查找最后执行的命令的返回值,我想在我的脚本中使用它,但它不起作用。
python 版本:3.7 库:子进程
我搜索了答案,但在 python 中找不到适合的答案。
我尝试了以下代码,但它不起作用:
#!/usr/bin/python
import subprocess
subprocess.call(["ls","-l"])
if $? == 0 :
print("is ok\n")
解决方案
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
推荐阅读
- javascript - createContextualFragment 只是以字符串形式从字符串中吐回 html
- java - 启动 MainActivity 作为新的意图打破了它的观点 onClicks 开始新的意图 android
- android - 如何将滑动阈值设置为屏幕的一半?
- c# - MVC Client 和 Api 在 IdentityServer4 中协同工作
- python - 我对此错误消息有疑问。TypeError: unsupported operand type(s) for -: 'str' and 'str'
- query-optimization - teradata,优化查询
- imagemagick - 使用 ImageMagick 裁剪和合并两个图像
- php - 基于 Woocommerce 3.3+ 中产品类别的自定义购物车项目货币符号
- javascript - 关于更改的 JQuery 不适用于动态更改
- angular - 以打字稿角度4将传单地图导出为JPG