Python program start

前端 未结 4 803
不思量自难忘°
不思量自难忘° 2021-02-05 05:33

Should I start a Python program with:

if__name__ == \'__main__\':
some code...

And if so, why? I saw it many times but don\'t have a clue about

4条回答
  •  [愿得一人]
    2021-02-05 06:15

    Guido Van Rossum suggests:

    def main(argv=None):
      if argv is None:
        argv = sys.argv
      ...
    
    if __name__ == "__main__":
        sys.exit(main())
    

    This way you can run main() from somewhere else (supplying the arguments), and if you want to exit with an error code just return 1 from main(), and it won't make an interactive interpreter exit by mistake.

提交回复
热议问题