简体   繁体   English

在 Python 中:如何获取从 Bash 运行的前一个进程的退出状态(即“$?”)?

[英]In Python: how can I get the exit status of the previous process run from Bash (i.e. “$?”)?

I have a Python script that should report success or failure of the previous command.我有一个 Python 脚本,它应该报告上一个命令的成功或失败。 Currently, I'm doing目前,我正在做

command && myscript "Success" || myscript "Failed"

What I would like to do is instead to be able to run the commands unlinked as in:我想做的是能够运行未链接的命令,如下所示:

command; myscript

And have myscript retrieve $?并让myscript检索$? , ie the exist status. ,即存在状态。 I know I could run:我知道我可以运行:

command; myscript $?

But what I'm really looking for is a Python way to retrieve $?但我真正在寻找的是一种检索$? from Python.来自 Python。

How can I do it?我该怎么做?


Since this is a strange request, let me clarify where it comes from.由于这是一个奇怪的要求,让我澄清一下它的来源。 I have a Python script that uses the pushover API to send a notification to my phone.我有一个 Python 脚本,它使用pushover API 向我的手机发送通知。

When I run a long process, I run it as process && notify "success" || notify "failure"当我运行一个很长的进程时,我将它作为process && notify "success" || notify "failure"运行process && notify "success" || notify "failure" process && notify "success" || notify "failure" . process && notify "success" || notify "failure" But sometimes I forget to do this and just run the process.但有时我忘记这样做并运行该过程。 At this point, I'd like to run "notify" on the still processing command line, and have it pick up the exit status and notify me.此时,我想在仍在处理的命令行上运行“notify”,让它获取退出状态并通知我。

Of course I could also implement the pushover API call in bash, but now it's become a question of figuring out how to do it in Python.当然,我也可以在 bash 中实现 pushover API 调用,但现在问题是如何在 Python 中实现它。

false; export ret=$?; ./myscript2.py

myscript2.py: myscript2.py:

#!/usr/bin/python

import os
print os.environ['ret']

Output:输出:

1

This may not be possible, because of how a script (of any language, not just Python) gets executed.这可能是不可能的,因为脚本(任何语言,而不仅仅是 Python)是如何执行的。 Try this: create a shell script called retcode.sh with the following contents:试试这个:创建一个名为retcode.sh的 shell 脚本,内容如下:

#!/bin/bash
echo $?

Make it executable, then try the following at a shell prompt:使其可执行,然后在 shell 提示下尝试以下操作:

foo # Or any other non-existent command
echo $?  # prints 127
foo
./retcode.sh  # prints 0

I'd have to double-check this, but it seems that all scripts, not just Python scripts, are run in a separate process that doesn't have access to the exit code of the previous command run by the "parent" shell process.我必须仔细检查这一点,但似乎所有脚本,而不仅仅是 Python 脚本,都在一个单独的进程中运行,该进程无权访问“父”shell 进程运行的前一个命令的退出代码. Which may explain why Python doesn't (as far as I can tell) give you a way to retrieve the exit code of the previous command like bash's $?这可以解释为什么 Python 没有(据我所知)给你一种方法来检索前一个命令的退出代码,比如 bash 的$? — because it would always be 0, no matter what. — 因为无论如何它总是 0。

I believe your approach of doing command; myscript $?我相信你的command; myscript $? command; myscript $? is the best way to achieve what you're trying to do: let the Python script know about the exit code of the previous step.是实现您正在尝试执行的操作的最佳方法:让 Python 脚本知道上一步的退出代码。

Update: After seeing your clarification of what you're trying to do, I think your best bet will be to modify your notify script just a little, so that it can take an option like -s or --status (using argparse to make parsing options easier, of course) and send a message based on the status code ("success" if the code was 0, "failure NN" if it was anything else, where NN is the actual code).更新:在看到您对您要做什么的澄清后,我认为您最好的办法是稍微修改您的notify脚本,以便它可以采用-s--status类的选项(使用argparse来制作当然,解析选项更容易)并根据状态代码发送消息(如果代码为 0,则为“成功”,如果是其他任何内容,则为“失败 NN”,其中 NN 是实际代码)。 Then when you type command without your little && notify "success" || notify "failure"然后当你在没有你的小&& notify "success" || notify "failure"情况下输入command&& notify "success" || notify "failure" && notify "success" || notify "failure" trick, while it's still running you can type notify -s $? && notify "success" || notify "failure"技巧,当它仍在运行时,您可以输入notify -s $? and get the notification you're looking for, since that will be the next thing that your shell runs after command returns.并获得您正在寻找的通知,因为这将是您的 shell 在command返回后运行的下一件事情。

But what I'm really looking for is a Python way to retrieve $?但我真正在寻找的是一种检索 $? from Python.来自 Python。

If you ran them as separate processes, then it's clearly impossible.如果您将它们作为单独的进程运行,那么这显然是不可能的。

An independent process cannot know how another process ended.一个独立的进程无法知道另一个进程是如何结束的。

You can 1) store the result in a file, 2) emit something from command , and pipe it to the script 3) run the command from myscript , and so on... but you need some kind of communication .您可以 1) 将结果存储在文件中,2) 从command发出一些内容,并将其通过管道传输到脚本 3) 从myscript运行命令,等等......但您需要某种通信

The simplest way, of course is command; myscript $?最简单的方法当然是command; myscript $? command; myscript $?

It is clearly not possible: the exit value of a process is only accessible to its parent, and no shells I know offer an API to allow next process to retrieve it.这显然是不可能的:一个进程的出口值只有其父访问,没有炮弹,我知道提供了一个API,允许下道工序进行检索。

IMHO, what is closer to your need would be:恕我直言,更接近您的需求的是:

process
myscript $?

That way, you can do it even if you started you process without thinking about notification.这样,即使您开始处理而不考虑通知,您也可以这样做。

You could also make the script able to run a process get the exit code and to its notification, or (depending on options given in command line) use an exit code given as parameter.您还可以使脚本能够运行一个进程,获取退出代码及其通知,或者(取决于命令行中给出的选项)使用作为参数给出的退出代码。 For example, you could have:例如,你可以有:

  • myscript process : runs process and does notifications myscript process :运行process并执行通知
  • myscript -c $? : only does notifications : 只做通知

argparse module can make that easy. argparse模块可以使这变得容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python作为“批处理”脚本(即从python运行命令) - python as a “batch” script (i.e. run commands from python) 我如何(我可以?)从命令中获取退出状态? - How do I (can I?) get the exit status from a command? 如何使用python获取脚本退出状态? - how can i get script exit status with python? Python:如何获取索引的负索引(str,beg = 0,end = len(string)),即从结束计数 - Python: how can I get negative indices out for index(str, beg=0, end=len(string)), i.e. counting from end Python - 如何从类中动态删除方法 - 即与setattr相反 - Python - how can I dynamically remove a method from a class — i.e. opposite of setattr 如何获得熊猫的分组窗口? 即喜欢从SQL到WINDOOW OVER…PARITION BY - How can I get grouped windows in pandas? I.e. like WINDOW OVER … PARTITION BY … from SQL 如何在python中从[u'92.91%\\ n']获取浮点值(即92.91%) - How to get float value (i.e. 92.91%) from [u' 92.91%\n '] in python 如何在CrawlerProcess完成后(即在process.start()之后的行中)获取统计信息值 - How to get stats value after CrawlerProcess finished, i.e. at line after process.start() 运行 JasperReport 库的 Python 应用程序 - 即没有 JasperServer - Python app to run JasperReport libraries - i.e. no JasperServer 如何通过在 python 中去除黑色像素,即 [0,0,0],从图像的 3D 数组中获取二维数组 - How to get 2D array from 3D array of an image by removing black pixels, i.e. [0,0,0], in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM