回答

收藏

if __name__ == "__main__": 怎么办?

技术问答 技术问答 364 人阅读 | 0 人回复 | 2023-09-11

给出以下代码有什么作用?if __name__ == "__main__":?
. M. I0 C* L( ~7 h/ e3 M
    # Threading exampleimport time,threaddef myfunction(string,sleeptime,lock,*args):    while True:        lock.acquire()        time.sleep(sleeptime)        lock.release()        time.sleep(sleeptime)if __name__ == "__main__":    lock = thread.allocate_lock()    thread.start_new_thread(myfunction,("Thread #: 1",2,lock))    thread.start_new_thread(myfunction,("Thread #: 2",2,lock))
    , n+ c" |( z* F! X' C  ]
               
- ?. ^3 x* T% m# ^$ q; _    解决方案:                                                               
9 ?5 Q5 t% D- t; a  U* ?                                                                简答它是模型代码,可以防止用户无意中调用脚本。以下是脚本中省略守卫的一些常见问题:
- ]" A+ `1 v8 x, u如果你在另一个脚本(例如(例如)import my_script_without_a_name_eq_main_guard)导入无保护脚本时,第二个脚本将触发第一个脚本在导入时运行并使用第二个脚本的命令行参数。这几乎总是一个错误。
- u$ i2 ]' y; l如果你在guardless 脚本中有一个自定义类,并将其保存到pickle 如果在另一个脚本中取消触发guardless 脚本的引入与上一个项目符号中概述的问题相同。
长答案为了更好地理解为什么以及它有多重要,我们需要退一步来理解 Python 如何初始化脚本,如何与模块导入机制交互。
" m0 W( k, T" @2 G4 Q; i每当 Python 当解释器读取源文件时,它会做两件事:: H: z# h4 J+ g* l( R/ `
它设置了一些特殊的变量,如__name__,然后9 M* c3 s* R, U- O2 I* f  t% `8 }
在执行文件中找到的所有代码。
让我们看看它是如何工作的,以及它和它__name__我们在 Python 脚本中经常看到的检查相关问题有什么关系?
  P8 u7 [( r6 L' R9 F代码示例让我们用稍微不同的代码示例来探索导入和脚本的工作方法。假设以下内容在名称中foo.py.5 p3 ?# X) B6 k  H
    # Suppose this is foo.py.print("before import")import mathprint("before functionA")def functionA():    print("Function A")print("before functionB")def functionB():    print("Function B {}".format(math.sqrt(100)))print("before __name__ guard")if __name__ == '__main__    functionA()    functionB()print("after __name__ guard")
    $ h1 A  c& K0 M$ t
特殊变量当 Python 当解释器读取源文件时,它首先定义了一些特殊的变量。在这种情况下,我们关心__name__变量。! H) s' }  }; T8 \( Y
当你的模块是主程序时
2 A( _: K8 Z& p2 {! I以模块(源文件)为主程序,例如
- B& K8 N7 z& \
    python foo.py
    : D+ L9 S6 Q' j3 v% h
解释器将硬编码字符串赋值"__main__"给__name__变量,即: o! ^4 H+ X- @' z- C% _
    # It's as if the interpreter inserts this at the top# of your module when run as the main program.__name__ = "__main__" 2 q; m# E3 g( G4 }7 _) ?
当您的模块被另一个导入时8 m; L8 A/ m2 v# b3 F3 q
另一方面,假设其他模块是主程序,并导入您的模块。这意味着主程序或主程序导入的其他模块中有这样的句子:: C$ I" _0 b1 p& p) [/ T
    # Suppose this is in some other main program.import foo
    $ f1 _' w- ^! H9 N- |
解释器会搜索你的foo.py文件(以及搜索其他一些变体),它将在执行该模块之前"foo"导入语句中的名称分配给__name__变量,即- Q$ M. Z+ x9 Q* L8 r
    # It's as if the interpreter inserts this at the top# of your module when it's imported from another module.__name__ = "foo"
    # d* u+ V. h' l( ]! K( j; w& X
代码执行模块设置特殊变量后,解释器执行模块中的所有代码,一次一句。您可能希望在带有代码示例的一侧打开另一个窗口,以便您可以按照此说明操作。# P6 }. l8 h# \- W7 l
总是
0 S. R( P% \* u( ^1 M[ol]它打印字符串"before import"(无引号)。
( `: l7 e( `) S/ }' w它加载math将模块分配给名称math. 这相当于替换import math以下内容(请注意)__import__是 Python 接受字符串并触发实际导入的低级函数:[/ol]
    7 g/ _3 I1 j' P  p7 z
    # Find and load a module given its string name,"math",# then assign it to a local variable called math.math = __import__("math")5 i( O2 B; Y4 d8 a- a, s* G2 C
[ol]它打印字符串"before functionA"。3 J1 |9 M3 }" c: Z, c# l! U
它执行def块,创建函数对象,然后将函数对象分配给一个名为 的变量functionA。6 d* d- p7 R0 H. ^+ ]
它打印字符串"before functionB"。4 N* c' e% ~) E- P
它执行第二个def块,创建另一个函数对象,然后分配给 变量functionB。# N( K9 I0 w) @$ ]4 l+ S" ?. ?2 b
它打印字符串"before __name__ guard"。[/ol]只有当你的模块是主程序时8 Z4 k' f. |- J! U! n' e" X/ _
[ol]假如你的模块是主程序,它会看到的__name__确实设置为"__main__"并调用两个函数打印字符串"Function A"和"Function B 10.0".[/ol]只有当您的模块被另一个导入时
0 u( S  o5 a# w$ X! }) b[ol](相反)假如你的模块不是主程序,而是由另一个程序导入,那么__name__will "foo",not "__main__",它将跳过if句子的主体。[/ol]总是! X5 C; W9 z6 ~# ^" M
[ol]它会"after __name__ guard"在两种情况下打印字符串。[/ol]概括) C& Z' L& k. k8 B* `# V% j
总之,在两种情况下打印以下内容:: l) o# U: n1 U9 }
    # What gets printed if foo is the main programbefore importbefore functionAbefore functionBbefore __name__ guardFunction AFunction B 10.0after __name__ guard# What gets printed if foo is imported as a regular modulebefore importbefore functionAbefore functionBbefore __name__ guardafter __name__ guard
    7 ]  S+ c; v( Y" O9 A. f
为什么这样工作?你自然会想知道为什么有人想要这个。嗯,有时候你想写一个。.py其他程序和/或模块都可以用作模块,也可以用作主程序本身。
7 [+ S6 C8 \9 N您的模块是一个库,但您想要一个脚本模式,它运行一些单元测试或演示。
  B* I/ O2 p5 K& A& d, q您的模块仅用作主程序,但它有一些单元测试,通过导入测试框架.py脚本和其他文件并运行特殊的测试功能来工作。您不希望它尝试运行脚本,因为它正在导入模块。. B9 i2 [1 k4 ~0 x$ R' G
您的模块主要用作主程序,但也为高级用户提供了对程序员友好的 API。
除此之外, Python 操作脚本只设置一些魔法变量并导入脚本,非常优雅。操作脚本是导入脚本模块的副作用。
: e6 f! U5 v' ?4 y/ q' @问答问:我能有多个__name__答:这很奇怪,但语言不会阻止你。8 D; k3 e. K$ l: v# O# p
假设以下内容是foo2.py. 如果你python foo2.py说命令行会发生什么?为什么?
    + P  [) S8 c- l$ O+ H2 a
    # Suppose this is foo2.py.import os,sys; sys.path.insert(0,os.path.dirname(__file__)) # needed for some interpretersdef functionA():    print("a1")    from foo2 import functionB    print("a2")    functionB()    print("a3")def functionB():    print("b")print("t1")if __name__ == "__main__":    print("m1")    functionA()    print("m2")print("t2")
    9 i, K, G( u0 A" |# _. C
现在,如果你取消取消了它__name__签入会发生什么?foo3.py:

    0 J6 R: _, e2 S' }/ L- I# Suppose this is foo3.py.import os,sys; sys.path.insert(0,os.path.dirname(__file__)) # needed for some interpretersdef functionA():    print("a1")    from foo3 import functionB    print("a2")    functionB()    print("a3")def functionB():    print("b")print("t1")print("m1")functionA()print("m2")print("t2")
    6 J2 M2 j) I3 c6 D. V1 H% O
当它被用作脚本时,它会做什么?导入模块时?

    . r" d2 m1 n; t2 \- @6 @# Suppose this is in foo4.py__name__ = "__main__"def bar():    print("bar")print("before __name__ guard")if __name__ == "__main__":    bar()print("after __name__ guard")0 c* Y* _' X7 Z4 P/ ]( ^2 O
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则