代码之家  ›  专栏  ›  技术社区  ›  Nadav Har'El

如何告诉Python停止源文件中间的解析?

  •  0
  • Nadav Har'El  · 技术社区  · 5 年前

    在其他语言中,这样做很容易。壳牌公司 exit 0 这基本上导致它之后的所有内容都无法解析。Perl有 __END__ . C或C++在文件结束之前不必忽略,但很容易用一个 #if 0 在某个时刻,最后 #endif 在文件末尾。

    我的问题是如何用Python实现这一点?我到处找,似乎找不到解决办法!

    print(1)
    exit(0)
    @$@(% # this is not correct Python
    

    此程序失败。这个 exit(0) 这没有帮助,因为Python仍然解析它之后的所有内容。更不用说了 显然,在导入的源文件中做不正确的事情(我的意图是停止读取此源文件-而不是退出整个程序)。我的问题是,我可以用什么来代替“exit(0)”行,使这个程序正常工作(打印“1”,就这样)。

    2 回复  |  直到 5 年前
        1
  •  3
  •   Fred Larson    5 年前

    将不希望解析的内容用三引号括起来:

    print(1)
    """
    @$@(% # this is not correct Python
    blah
    dee
    blah
    blah
    """
    
        2
  •  0
  •   Mark    5 年前

    您可以引发一个异常,假设您的某些条件是否满足

    在导入的文件中

    print("hi")
    my_condition = True
    if my_condition:
        raise Exception
    print("nope")
    

    然后在try块中包装导入

    try:
        import your_module
    except Exception:
        print("source not fully read")