[英]How to use last executed command's return code in python shell script
Dollar question mark ($?) is used to find the return value of the last executed command and I want to use it in my script but it does not work.美元问号 ($?) 用于查找上次执行命令的返回值,我想在我的脚本中使用它但它不起作用。
python version : 3.7 Library : subprocess python 版本:3.7 库:子进程
I searched the answer but I can't find the suit answer in python.我搜索了答案,但在 python 中找不到适合的答案。
I tried the following code, but it doesn't work :我尝试了以下代码,但它不起作用:
#!/usr/bin/python
import subprocess
subprocess.call(["ls","-l"])
if $? == 0 :
print("is ok\n")
subprocess.call
will return the code and you can store it inside variable: 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
Prints:印刷:
... the result of `ls -l`
is ok
call
returns an object with a returncode
attribute you can check. call
返回一个带有returncode
属性的对象,您可以检查它。
result = subprocess.call(["ls", "-l"])
if result.returncode == 0:
print("is ok")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.