开发者

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

开发者 https://www.devze.com 2023-02-22 04:46 出处:网络
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.

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)?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消