我可以告诉Python忽略文件的其余部分和/或退出而不引发异常,就像到达文件末尾一样吗?

问题描述 投票:-1回答:2

当我执行Python脚本(*)并到达文件末尾时,我返回到命令提示符,没有显示任何其他消息。我想知道是否有命令在文件末尾之前“退出”(结束解析/执行)脚本(或者只是忽略所有直到末尾),所以我可以在该点以下留下注释,未完成的代码等。

[当我使用quit()exit()raise SystemExit(...)等时,所有这些都引发异常,导致出现“跟踪”消息。 (La)TeX中是否有类似\endinput的内容,可让解释器仅忽略文件的其余部分,就好像已经到达文件末尾一样?]

关于“如何退出...而没有回溯...”的问题在SO上已被多次问及回答,但答案始终是“你不能”; “一定是允许清理/调试的方法……”(有人提到os._exit(),然后其他人说“由于清理不完全,所以不可以”)。我认为这是指从“某物内”退出。我正在寻找一个命令,说“这是文件的结尾!”

PS:我知道我可以将文件的其余部分放在"""..."""中,但这仅适用于在“暂存区域”中已经有多行注释的地方。我真的在寻找类似\ endinput命令的东西。

(*)PS2:这可能是相关的,所以我提到:我实际上是在pythonanywhere.com上“运行”文件。单击“运行”将在其服务器上执行命令_pa_run("filename")(可能是由他们执行的自定义命令),但是我认为对于在任何其他环境中执行的Python脚本来说,它可能是相同的。

编辑:根据要求,我将添加一个特定的示例(尽管为简便起见,这是不现实的:]

def Newton(f,x0,eps,N):
    """here I implement Newton's method"""
    #(...) iterations go here (...)
    return x
def f(x): function for testing
   return ...

quit() # Unfortunately this raises a Traceback, at least when the file is "Run" 
# on pythonanywhere.com. I'd like to avoid this. I would simply like everything
# to be ignored after this point, let's say "for convenience", to simplify.
# I'd like to know whether it is possible, not whether in some situations I
# could or should do otherwise.

def f(x):# this is another function for testing
   return [something else]
[...] # another formula to try. This is just a snippet and might not compile.
def Newton(...):# the old version. Not yet trashed because maybe needed.
      # Would have to rename this if the whole file is read by the compiler.

# Below follow more routines which are part of the final version of this file, 
# but I don't want to compile all of them each time, while I fiddle around with
# the latest addition, for now put the beginning of the file.
# OTOH I would like to have that code in the same file for easier copy-paste in
# case I need some parts of it while developing the new stuff at top of file.
python exit eof traceback systemexit
2个回答
1
投票

我想知道是否有命令在文件结尾之前“退出”(结束解析/执行)脚本>

我认为您关于如何解释和执行Python脚本的思维模型与实际发生的情况不一致。首先,解析脚本与执行脚本并不相同,因此您需要单独考虑它们。

似乎LaTeX语法类似于编程语言,这使您难以寻找与\endinput类似的概念,而其中根本不存在。我认为没有一种方法可以随时停止脚本的“解析”,如果您希望脚本的一部分不“执行”,则需要调用exit或[C0 ],然后再将其包裹在注释栏中。


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.