exit failed script run (python) - python

I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.
I hope this is enough information; let me know if more details are required to help me.

Are you just looking for the exit() function?
import sys
if 1 < 0:
print >> sys.stderr, "Something is seriously wrong."
sys.exit(1)
The (optional) parameter of exit() is the return code the script will return to the shell. Usually values different than 0 signal an error.

You can use sys.exit() to exit. However, if any code higher up catches the SystemExit exception, it won't exit.

You can raise exceptions to identify error conditions. Your top-level code can catch those exceptions and handle them appropriately. You can use sys.exit to exit. E.g., in Python 2.x:
import sys
class CameraInitializationError(StandardError):
pass
def camera_test_1():
pass
def camera_test_2():
raise CameraInitializationError('Failed to initialize camera')
if __name__ == '__main__':
try:
camera_test_1()
camera_test_2()
print 'Camera successfully initialized'
except CameraInitializationError, e:
print >>sys.stderr, 'ERROR: %s' % e
sys.exit(1)

You want to check the return code from the c++ program you are running, and exit if it indicates failure. In the code below, /bin/false and /bin/true are programs that exit with error and success codes, respectively. Replace them with your own program.
import os
import sys
status = os.system('/bin/true')
if status != 0:
# Failure occurred, exit.
print 'true returned error'
sys.exit(1)
status = os.system('/bin/false')
if status != 0:
# Failure occurred, exit.
print 'false returned error'
sys.exit(1)
This assumes that the program you're running exits with zero on success, nonzero on failure.

Related

Why my python code terminates even though I have proper exception handling?

I have the following python code:
try:
subprocess.check_output('service uwsgi stop;pkill -f uwsgi', shell = True)
except:
sys.exit(0)
it should return always 0 but when I run it, it prints 'Terminated' and then I receive a non-zero return code.
Right now, sys.exit(0) will only be called when an exception is raised. To ensure that it is called every time, add a finally statement:
try:
subprocess.check_output('service uwsgi stop;pkill -f uwsgi', shell = True)
except:
# Handle the exception
finally:
sys.exit(0)

Get exit status of last command in Python script

How can I get the exist status (if command succeed or not) of any line in Python?
For example in bash, $? will tell me the last exist status of any command.
I need it to know if my connection to FTP server was successful or not.
Have you tried using a try/catch? If there was an error while executing the command, an exception will be raised. You can retrieve it with the sys module.
Example code:
import sys
try:
run_command()
except:
e = sys.exc_info()[0]
print(e)
If it is a function you call, it should have a retrun code you can collect like
retVal = doSomething()
Then you can check what happened.

How do I exit Python if run from command line, otherwise print stack trace

I want to exit Python if I encounter an exception in my function if that function is being executed from the command line, but want to raise an exception and print a stack trace if the my function is not run from the command line.
Right now I have
try:
#...
except Exception as e:
print('ERROR: Some useful message')
if __name__ == '__main__':
raise SystemExit
else:
raise e
but I feel like I'm either doing too much here, or too little.
Is there an idiomatic way to get a stack trace with the original exception when my function is run from the command line; but simply exit if it is being run from the command line?
The better way would be to do this:
import sys
def func():
do_actual_processing()
if not successful:
raise Exception("Yadayada")
if __name__ == '__main__'
try:
func()
except Exception as e:
sys.exit(1)
That is, the function itself does not need to be concerned with whether or not it is run from command line.

sh to py conversion

I'm currently converting a shell script to python and I'm having a problem. The current script uses the results of the last ran command like so.
if [ $? -eq 0 ];
then
testPassed=$TRUE
else
testPassed=$FALSE
fi
I have the if statement converted over just not sure about the $? part. As I am new to python I'm wondering if there is a similar way to do this?
You should look into the subprocess module for that. There is a check_call method for looking into exit codes (this is one method, there are others as well). As the manual mentions:
Run command with arguments. Wait for command to complete. If the
return code was zero then return, otherwise raise CalledProcessError.
The CalledProcessError object will have the return code in the
returncode attribute
An example of this is:
import subprocess
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command)
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
This will also include output, which you can either redirect to a file or suppress like so:
import subprocess
import os
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
Here is an example of a call with a non-zero exit code:
import subprocess
import os
command=["grep", "mystring", "/home/cwgem/testdir/test.txt"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
Output:
$ python process_exitcode_test.py
Program exited with exit code 1
Which is captured as an exception that you can handle as above. Note that this will not handle exceptions such as access denied or file not found. You will need to handle them on your own.
You might want use the sh module. It makes shell scripting in Python much more pleasant:
import sh
try:
output = sh.ls('/some/nen-existant/folder')
testPassed = True
except ErrorReturnCode:
testPassed = False

do not understand this use of sys module

Here is code from a tutorial in A Byte of Python:
import sys
filename = 'poem.txt'
def readfile(filename):
#Print a file to standard output
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
if len(sys.argv) < 2:
print 'No action specified'
sys.exit() //<--This is where the error is occurring
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:] #fetches sys.argv[1] without first 2 char
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version: Prints the version number
--help: Displays this help'''
else:
print 'Unknown option'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
When I run this code, this is the error that appears:
Traceback (most recent call last):
File "C:/Python/sysmodulepr.py", line 17, in <module>
sys.exit()
SystemExit
I don't understand why. Please help.
It's telling you that sys.exit() has executed on line 17 of your program.
The entry for for sys.exit in the Python documentation tells you that this exits your program.
There's no way this line can execute without producing other output, so I think there's something missing in the question.
If you're using IDLE, it will print the stack anyway. Try running your script from the command line, it won't print that error message when executed outside the IDE.
It's not an error. sys.exit() raises SystemExit exception to allow try:... finally block to cleanup used resources
Try in Idle:
import sys
sys.exit()
From documentation for sys.exit():
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
edit
The error shouldn't be normally printed unless you're trying to run the script in some interactive interpreters (for example Idle).
It's nothing to worry about, but the script looks like it's standalone, so you should use it as such.

Categories

Resources