简体   繁体   English

如何在python shell脚本中使用上次执行命令的返回码

[英]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.

相关问题 如何使用命令执行python脚本 - How to executed python script with command 如何用python获取shell中执行的命令&arguments - How to get the command & arguments that was executed in shell with python 如何使用“代码”。 python脚本中的命令 - how to use "code ." command in python script 如何在Python中获取已执行命令的返回值 - How to get return value of a executed command in Python 如何在python解释器shell中重复最后一个命令? - How to repeat last command in python interpreter shell? 在 python 脚本中启动一个 shell 命令,等待终止并返回到脚本 - Launch a shell command with in a python script, wait for the termination and return to the script 如何获取python执行的shell命令的最终输出 - How to get the final output of of shell command executed by python 如何在python中的变量中存储执行的shell命令的结果? - How to store the result of an executed shell command in a variable in python? 如何在Django Shell中执行Python表达式之前和之后运行脚本? - How to run a script before and after a Python expression is executed in Django shell? 编辑后如何在 Python shell 中更新已执行的脚本导入? - How to update an executed script import in the Python shell after editing it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM