How safe is it to use sys.exit() in custom commands

39 views
Skip to first unread message

phep

unread,
Sep 29, 2017, 5:13:50 PM9/29/17
to Django users
Hi,

Executive summary : everything's in the subject line.

Boring details :

I have a Django application where I use a lot of custom commands, most being
designed to be launched mostly by cron-jobs or other bash scripts of some
sorts. In this respect, the exit code value may be of utmost importance.

Up until now, as I focused on the business logic part, when things went
wrong I just raised exceptions so that the return code was set to 1. So good
so far. The problem is the output is rather uselessly verbose then. I'm in
the process of fixing things up in order to have some more concise output on
failures.

It seems to me I once read in the doc that one should not use sys.exit() in
custom commands, but can't find exactly where it was - but I found some
allusions about this in StackOverflow comments. Yet I just sgoogumbled on
this ticket https://code.djangoproject.com/ticket/25419 where it seems safe
to use it.

AFAIAC, I would be using sys.exit() almost exclusively at the top level
inside the handle() method, while testing sub-routines return values of
catching exceptions. Tests I've run seems show this is working as I'd
expected, but I'd like to be sure there is no hidden traps before to deploy
this code on the production server.

So what is your take on this question ?

Thanks in advance,

phep

Tim Graham

unread,
Sep 30, 2017, 2:58:15 PM9/30/17
to Django users
I don't know of any reason why that would be unsafe. You'll find several uses of sys.exit() in Django's built in commands located in django/core/management/commands.
Reply all
Reply to author
Forward
0 new messages