This may not be possible due to the way the script is executed (any language, not just Python). Try it: create a shell script called retcode.sh with the following contents:
#!/bin/bash echo $?
Make it executable, then try the following on the command line:
foo
I would have to double check this, but it seems that all scripts, not just Python scripts, are run in a separate process that does not have access to the output code of the previous command executed by the "parent" shell process. What can explain why Python does not (as far as I can tell) give you a way to get the exit code of a previous command, for example bash $? , because there will always be 0, whatever.
I believe your approach to command; myscript $? execution command; myscript $? command; myscript $? is the best way to achieve what you are trying to do: let the Python script know about the exit code of the previous step.
Update:. After seeing your clarification about what you are trying to do, I think your best bet is to slightly modify your notify script so that it can have an option like -s or --status (using argparse , of course, to simplify the analysis options) and send a message based on the status code (“success” if the code was 0, “failed NN” if it was something else, where NN is the actual code). Then, when you type command without your little trick && notify "success" || notify "failure" && notify "success" || notify "failure" while it is still working, can you enter notify -s $? and get the notification you are looking for, as this will be the next thing that your shell starts after command returns.
rmunn source share