473,322 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

sys.exit()

In a code such as:

if len(sys.argv) < 2:
print "I need arguments!"
sys.exit(1)

Is sys.exit() really a good choice? Is there something more elegant? (I
tried return but it is valid only in a function)
--
--
Every sufficiently advanced magic is indistinguishable from technology
- Arthur C Anticlarke
Jul 18 '05 #1
12 88268
"Ivan Voras" <iv****@fer.hr> wrote in news:bm**********@bagan.srce.hr:
In a code such as:

if len(sys.argv) < 2:
print "I need arguments!"
sys.exit(1)

Is sys.exit() really a good choice? Is there something more elegant? (I
tried return but it is valid only in a function)


More elegant might be to put your code in a function which would let you
use return, although even then you need to call sys.exit somewhere if you
want to set a return code. Remember that sys.exit just throws an exception,
so you can always catch it further out if you need to. Also you can combine
the print into the call to sys.exit and save a line:

import sys

def main(args):
if len(args) < 2:
sys.exit("I need arguments!")

print "rest of program..."

if __name__=='__main__':
main(sys.argv)

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #2
Ivan Voras wrote:

In a code such as:

if len(sys.argv) < 2:
print "I need arguments!"
sys.exit(1)

Is sys.exit() really a good choice? Is there something more elegant? (I
tried return but it is valid only in a function)


sys.exit() is the proper, defined, cross-platform way to exit from
a program and return a value to the calling program. Change your
definition of elegant and you could consider it easily the most elegant
of all solutions. ;-)

-Peter
Jul 18 '05 #3
Peter Hansen wrote:
Ivan Voras wrote:
Is sys.exit() really a good choice? Is there something more elegant?
(I tried return but it is valid only in a function)
sys.exit() is the proper, defined, cross-platform way to exit from
a program and return a value to the calling program. Change your
definition of elegant and you could consider it easily the most
elegant of all solutions. ;-)


Ok. :)

(Just for the record: I was looking for something that doesn't require a
module import. But it is not important.)

--
--
Every sufficiently advanced magic is indistinguishable from technology
- Arthur C Anticlarke
Jul 18 '05 #4
Ivan Voras wrote:
In a code such as:

if len(sys.argv) < 2:
print "I need arguments!"
sys.exit(1)

Is sys.exit() really a good choice? Is there something more elegant? (I
tried return but it is valid only in a function)


An alternative that I often choose is:

raise SystemExit("I need arguments!")

This is the same in one line, and I think it is more elegant, because it
is higher-level: you are not using the low-level interface of error codes,
a non-programmer may not understand what '1' means, usually it means success
so that can be very confusing. I prefer raise SystemExit.

Gerrit.

--
30. If a chieftain or a man leave his house, garden, and field and
hires it out, and some one else takes possession of his house, garden, and
field and uses it for three years: if the first owner return and claims
his house, garden, and field, it shall not be given to him, but he who has
taken possession of it and used it shall continue to use it.
-- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Kom in verzet tegen dit kabinet:
http://www.sp.nl/

Jul 18 '05 #5
Gerrit Holl wrote:
An alternative that I often choose is:

raise SystemExit("I need arguments!")

This is the same in one line, and I think it is more elegant, because
it
is higher-level: you are not using the low-level interface of error


Yes, I agree. This is what I was looking for (as always, it was obvious
:) ), thanks. Only, what error code is returned for this termination method?

--
--
Every sufficiently advanced magic is indistinguishable from technology
- Arthur C Anticlarke
Jul 18 '05 #6
Ivan Voras wrote:
Gerrit Holl wrote:
An alternative that I often choose is:

raise SystemExit("I need arguments!")

This is the same in one line, and I think it is more elegant, because
it
is higher-level: you are not using the low-level interface of error


Yes, I agree. This is what I was looking for (as always, it was obvious
:) ), thanks. Only, what error code is returned for this termination method?


For a string, I believe it is 1, although I don't know when this holds and
when it doesn't - I don't care for myself, so I never tried to find out, really ;)

Gerrit.

--
258. If any one hire an ox-driver, he shall pay him six gur of corn per
year.
-- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Kom in verzet tegen dit kabinet:
http://www.sp.nl/

Jul 18 '05 #7
On Thu, 09 Oct 2003 20:44:55 +0200, Gerrit Holl wrote:
Ivan Voras wrote:
Gerrit Holl wrote:
> An alternative that I often choose is:
>
> raise SystemExit("I need arguments!")
>
> This is the same in one line, and I think it is more elegant, because
> it
> is higher-level: you are not using the low-level interface of error


Yes, I agree. This is what I was looking for (as always, it was obvious
:) ), thanks. Only, what error code is returned for this termination method?


For a string, I believe it is 1, although I don't know when this holds and
when it doesn't - I don't care for myself, so I never tried to find out, really ;)


Actually, SystemExit is a *lower* level operation. From the docs:
[ http://www.python.org/doc/current/lib/module-sys.html ]
================================================== ==============
exit( [arg])

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. The optional argument arg can be an integer
giving the exit status (defaulting to zero), or another type of
object. If it is an integer, zero is considered ``successful
termination'' and any nonzero value is considered ``abnormal
termination'' by shells and the like. Most systems require it to be in
the range 0-127, and produce undefined results otherwise. Some systems
have a convention for assigning specific meanings to specific exit
codes, but these are generally underdeveloped; Unix programs generally
use 2 for command line syntax errors and 1 for all other kind of
errors. If another type of object is passed, None is equivalent to
passing zero, and any other object is printed to sys.stderr and
results in an exit code of 1. In particular, sys.exit("some error
message") is a quick way to exit a program when an error occurs.
================================================== ==============

So SystemExit is called by sys.exit. And one can use:

sys.exit('I need arguments!')

Thus it would seem that sys.exit is higher level, and probably a bit more
stable and portable.
-- George

Jul 18 '05 #8
George Young wrote:
So SystemExit is called by sys.exit. And one can use:

sys.exit('I need arguments!')

Thus it would seem that sys.exit is higher level, and probably a bit more
stable and portable.


Ah, yes. I was probably confused with another function, I think with
os._exit. I don't really understand why _exit is in the os module
while exit is in the sys module; I have grown accostumed to raising
SystemExit, but I can de-grow it again I guess ;)

Gerrit.

--
240. If a merchantman run against a ferryboat, and wreck it, the master
of the ship that was wrecked shall seek justice before God; the master of
the merchantman, which wrecked the ferryboat, must compensate the owner
for the boat and all that he ruined.
-- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Kom in verzet tegen dit kabinet:
http://www.sp.nl/

Jul 18 '05 #9
BDFL has said: http://www.artima.com/weblogs/viewpost.jsp?thread=4829

"Ivan Voras" <iv****@fer.hr> wrote in message
news:bm**********@bagan.srce.hr...
In a code such as:

if len(sys.argv) < 2:
print "I need arguments!"
sys.exit(1)

Is sys.exit() really a good choice? Is there something more elegant? (I
tried return but it is valid only in a function)
--
--
Every sufficiently advanced magic is indistinguishable from technology
- Arthur C Anticlarke
Jul 18 '05 #10
Quoth "Ivan Voras" <iv****@fer.hr>:
| In a code such as:
|
| if len(sys.argv) < 2:
| print "I need arguments!"
| sys.exit(1)
|
| Is sys.exit() really a good choice? Is there something more elegant? (I
| tried return but it is valid only in a function)

Your question has already been answered many times over, so I will
instead note something about the above that is rather common but
wrong. "print" writes to sys.stdout (unless instructed otherwise),
and in the present case this output should certainly go to sys.stderr.
The easiest way to do that in recent versions of python (2.0 and
later) is "print >> sys.stderr".

Donn Cave, do**@drizzle.com
Jul 18 '05 #11
"Donn Cave" <do**@drizzle.com> wrote in news:1065757907.371391@yasure:
| Is sys.exit() really a good choice? Is there something more elegant? (I
| tried return but it is valid only in a function)

Your question has already been answered many times over, so I will
instead note something about the above that is rather common but
wrong. "print" writes to sys.stdout (unless instructed otherwise),
and in the present case this output should certainly go to sys.stderr.
The easiest way to do that in recent versions of python (2.0 and
later) is "print >> sys.stderr".


Note that the suggestions to use "sys.exit(message)" or "raise
SystemExit(message)" will send the message to sys.stderr. This is probably
easier than doing it explicitly in a separate print statement, plus it has
the advantage that if you want to catch the exit for any reason you also
catch the error message.

I've actually ended up doing this on occasion in unit tests, if you are
testing something that should cause a fatal error its a lot easier if the
error message is encapsulated in the SystemExit exception.

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #12
Quoth Duncan Booth <du****@NOSPAMrcp.co.uk>:
| "Donn Cave" <do**@drizzle.com> wrote in news:1065757907.371391@yasure:
....
|> Your question has already been answered many times over, so I will
|> instead note something about the above that is rather common but
|> wrong. "print" writes to sys.stdout (unless instructed otherwise),
|> and in the present case this output should certainly go to sys.stderr.
|> The easiest way to do that in recent versions of python (2.0 and
|> later) is "print >> sys.stderr".
|
| Note that the suggestions to use "sys.exit(message)" or "raise
| SystemExit(message)" will send the message to sys.stderr. This is probably
| easier than doing it explicitly in a separate print statement, plus it has
| the advantage that if you want to catch the exit for any reason you also
| catch the error message.
|
| I've actually ended up doing this on occasion in unit tests, if you are
| testing something that should cause a fatal error its a lot easier if the
| error message is encapsulated in the SystemExit exception.

That's right, it does work and it is easier. But please don't think
of print >> sys.stderr as something that's hard, lest that lead to
code like distutils that just neglects to do it.

distutils perhaps has the excuse that it had this problem before there
was a solution, but it's a good example of the problem. It's natural
to want to save the output of distutils to disk - I think it's really a
good practice to do this routinely so later you know how an application
was built, what went into it and where it got installed. In this case,
you'd always redirect both stdout and stderr, with a shell command line
like 'python setup.py > make.log 2>&1', so it would seem that the choice
between stdout and stderr would not matter. But it matters a lot, because
when stdout is a disk file, it's block buffered. That means the actual
flush to disk may be deferred for some time. Meanwhile, the applications
and processes that distutils invokes (cc, etc.) write immediately to disk
because if nothing else their output buffers flush when they exit. So
your log file starts with a bunch of diagnostic output from cc, and only
later gets to the distutils output that announces it's going to run cc.
Completely unreadable. stderr is always line buffered.

Donn Cave, do**@drizzle.com
Jul 18 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Guinness Mann | last post by:
Pardon me if this is not the optimum newsgroup for this post, but it's the only .NET newsgroup I read and I'm certain someone here can help me. I have a C# program that checks for an error...
1
by: Brendan Miller | last post by:
I am trying to close my application using Application.exit() in the frmMain_Closing event. When the form closes the process does not. My application only has one form (no other classes either). ...
4
by: Bob Day | last post by:
Using VS 2003, VB.net... I am confused about the Application.Exit method, where the help states "This method does not force the application to exit." Aside from the naming confusion, how do I...
1
by: =?Utf-8?B?VGFvZ2U=?= | last post by:
Hi All, When I use applcation.exit() in winForm application, the form closed, but the process is still going!! ( The debug process is still running if debug in VS IDE). Environment.Exit(0) works...
16
by: Laurent Deniau | last post by:
I would like to know if the use of the pointer ref in the function cleanup() below is valid or if something in the norm prevents this kind of cross-reference during exit(). I haven't seen anything...
11
by: yawnmoth | last post by:
To quote from <http://php.net/function.include>, "Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value." ...
11
by: =?Utf-8?B?U3RldmVEQjE=?= | last post by:
Hi all. I'm using VS 2008 Express C++. I created a console application back in 1999, and updated it for VC++ 6.0 in 2001. I've updated again this past month, and have found enough differences...
39
by: mathieu | last post by:
Hi there, I am trying to reuse a piece of code that was designed as an application. The code is covered with 'exit' calls. I would like to reuse it as a library. For that I renamed the 'main'...
0
by: Gary Robinson | last post by:
In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit with: exit() But I don't see exit() mentioned as a built-in function; rather the Python Library Reference says we...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.