Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I indicate that my Python shell script is returning an error?

Tags:

python

shell

I’m writing a shell script in Python (#!/usr/bin/env python). I’m a bit new to shell scripting in general, so apologies if I’m misunderstanding something.

My current understanding is that if my shell script works successfully, I should call sys.exit() to indicate that it’s succeeded (i.e. return 0).

If I’ve encountered an error (specifically, that the user has passed in an argument that I’m not expecting), what should I return, and how?

Is it okay just to call sys.exit() with any non-zero value, e.g. sys.exit(1)?

like image 434
Paul D. Waite Avatar asked Apr 06 '11 09:04

Paul D. Waite


2 Answers

Any non zero value will do. So sys.exit(1) is correct. These error codes are useful for using scripts on the command line:

python test.py && echo 'success'

The above will not print 'success' when your script returns anything but 0.

like image 38
Marijn van Vliet Avatar answered Oct 21 '22 02:10

Marijn van Vliet


Most Shell utilites have various return values depending on the error that occurs.

The standard is when exiting with a status code of 0, it means the execution ended successfully.

For other error codes, this is highly dependant on the utility itself. You're most likely to learn about error codes in the man pages of the aforementioned utilities.

Here's a simple example of the ls man page:

Exit status:
   0      if OK,

   1      if minor problems (e.g., cannot access subdirectory),

   2      if serious trouble (e.g., cannot access command-line argument).

It's highly recommended that you document properly your utility's exit codes in order for its users to use it correctly.

like image 154
SirDarius Avatar answered Oct 21 '22 03:10

SirDarius