简体   繁体   English

获取嵌套函数的退出状态?

[英]Get Exit Status of a Nested Function?

I have a function called within a different function. 我在另一个函数中有一个函数。 In the nested function, various errors (eg improper arguments, missing parameters, etc.) should result in exit status 1. Something like: 在嵌套函数中,各种错误(例如,不正确的参数,缺少的参数等)都将导致退出状态1。

if not os.path.isdir(filepath):
    print('Error: could not find source directory...')
    sys.exit(1)

Is this the correct way to use exit statuses within python? 这是在python中使用退出状态的正确方法吗? Should I have, instead, 我是否应该

return sys.exit(1)

??? ??? Importantly, how would I reference the exit status of this nested function in the other function once the nested function had finished? 重要的是,一旦嵌套函数完成,我将如何在另一个函数中引用此嵌套函数的退出状态?

sys.exit() raises a SystemExit exception . sys.exit()引发SystemExit异常 Normally, you should not use it unless you really mean to exit your program. 通常,除非确实要退出程序否则不要使用它

You could catch this exception: 您可以捕获以下异常:

try:
    function_that_uses_sys.exit()
except SystemExit as exc:
    print exc.code

The .code attribute of the SystemExit exception is set to the proposed exit code. SystemExit异常的.code属性设置为建议的退出代码。

However, you should really use a more specific exception, or create a custom exception for the job. 但是,您实际上应该使用更具体的异常,或者为作业创建一个自定义异常。 A ValueError might be appropriate here, for example: ValueError在这里可能是适当的,例如:

if not os.path.isdir(filepath):
    raise ValueError('Error: could not find source directory {!r}'.format(filepath))

then catch that exception: 然后捕获异常:

try:
    function_that_may_raise_valueerror()
except ValueError as exc:
    print "Oops, something went wrong: {}".format(exc.message)

By using sys.exit , you typically signal that you want the entire program to end. 通过使用sys.exit ,您通常会发出信号,表示您希望整个程序结束。 If you want to handle the error in a calling function, you should probably have the inner function raise a more specific exception instead. 如果要处理调用函数中的错误,则可能应该让内部函数引发一个更具体的异常。 (You could catch the exception raised by SystemExit, but it would be a rather awkward way to pass error information out.) (您可以捕获SystemExit引发的异常,但这是将错误信息传递出去的相当尴尬的方法。)

I guess that the right thing to do is this: 我猜正确的做法是这样的:

if not os.path.isdir(filepath):
    raise ValueError('the given filepath is not a directory')

However, the code as it stands still could be improved. 但是,目前的代码仍然可以改进。 One point is that a path to a file should never be a directory, so that is not an exceptional state. 有一点是,文件路径永远不应是目录,因此这不是一种例外状态。 Maybe what you want is to just name it path without adding an unintended connotations. 也许你想要的是只是它命名path不添加意外的内涵。

Further, and that has actual functional implications, you are still not guaranteed to be able to access a directory there even if isdir() returns true! 此外,这具有实际的功能含义,即使isdir()返回true,也仍然不能保证能够访问该目录! The reason is that something could have switched the thing under your feet, typically a malicious attacker, or, more simple, you could simply not have the rights to access it. 原因是某些东西可能已将其转移到您的脚下,通常是恶意攻击者,或更简单地说,您根本无权访问它。 If you care, you should rather just open the directory and handle the according errors instead of trying in advance to determine if something in the future will fail. 如果需要的话,您应该只打开目录并处理相应的错误,而不是提前尝试确定将来是否会失败。 This is in general a better approach, as the "normal" code doesn't get cluttered by such checks and you also don't pay any albeit small performance penalty except when an error occurs. 通常,这是一种更好的方法,因为“常规”代码不会因此类检查而变得杂乱无章,并且除了发生错误时,您也不会付出任何小的性能损失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM