|
给出以下代码有什么作用?if __name__ == "__main__":?) F; N/ _' A7 @# n% z" R( b
# 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))1 E. [- r- p# d0 p
' w) C/ y& ]9 P4 t1 r
解决方案: 6 z- y. |2 o% i3 ?' h+ x+ t
简答它是模型代码,可以防止用户无意中调用脚本。以下是脚本中省略守卫的一些常见问题:
$ T, X$ L& Y0 B; n如果你在另一个脚本(例如(例如)import my_script_without_a_name_eq_main_guard)导入无保护脚本时,第二个脚本将触发第一个脚本在导入时运行并使用第二个脚本的命令行参数。这几乎总是一个错误。
. F: ?+ _9 x5 t5 E' A4 @# W如果你在guardless 脚本中有一个自定义类,并将其保存到pickle 如果在另一个脚本中取消触发guardless 脚本的引入与上一个项目符号中概述的问题相同。长答案为了更好地理解为什么以及它有多重要,我们需要退一步来理解 Python 如何初始化脚本,如何与模块导入机制交互。
3 o2 o* P5 p: R7 X每当 Python 当解释器读取源文件时,它会做两件事:$ A! N6 g; E8 b+ W* r5 e4 \* l
它设置了一些特殊的变量,如__name__,然后
: O( \" i. k: O在执行文件中找到的所有代码。让我们看看它是如何工作的,以及它和它__name__我们在 Python 脚本中经常看到的检查相关问题有什么关系?/ \( p/ o) U9 Y
代码示例让我们用稍微不同的代码示例来探索导入和脚本的工作方法。假设以下内容在名称中foo.py.
1 x$ |3 g8 r/ L& e# 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")
' g- h; U: J, g/ ?* ]3 l7 z 特殊变量当 Python 当解释器读取源文件时,它首先定义了一些特殊的变量。在这种情况下,我们关心__name__变量。
7 c' J& d" w8 D9 R- s5 d( _( z当你的模块是主程序时9 { I3 t( l5 B5 c6 O2 \. f# c& g
以模块(源文件)为主程序,例如, Y2 k0 R9 X, T) W* x9 k, i! L8 W
python foo.py* c6 h/ E; z1 { r) I# ?7 g* U
解释器将硬编码字符串赋值"__main__"给__name__变量,即! H. H( {+ \3 V9 I
# It's as if the interpreter inserts this at the top# of your module when run as the main program.__name__ = "__main__"
6 R# I6 I% s( f6 H( H! J; F 当您的模块被另一个导入时
2 I4 x! ]" J) h另一方面,假设其他模块是主程序,并导入您的模块。这意味着主程序或主程序导入的其他模块中有这样的句子:
1 v8 \! N0 Z. t9 ^# Suppose this is in some other main program.import foo
- [/ x- S% C/ k- K5 [ 解释器会搜索你的foo.py文件(以及搜索其他一些变体),它将在执行该模块之前"foo"导入语句中的名称分配给__name__变量,即
9 Z5 i$ c' Z/ ]# It's as if the interpreter inserts this at the top# of your module when it's imported from another module.__name__ = "foo"2 `9 y) \: U' `$ d, d" h! U( ~& x
代码执行模块设置特殊变量后,解释器执行模块中的所有代码,一次一句。您可能希望在带有代码示例的一侧打开另一个窗口,以便您可以按照此说明操作。
7 M# a- S! s/ K- n5 \( V! t( |总是" ~# s# e# ~9 f: z* _1 _5 }' D
[ol]它打印字符串"before import"(无引号)。
5 t7 M% v$ ?6 A它加载math将模块分配给名称math. 这相当于替换import math以下内容(请注意)__import__是 Python 接受字符串并触发实际导入的低级函数:[/ol]
/ t3 L. T7 n' Y# Find and load a module given its string name,"math",# then assign it to a local variable called math.math = __import__("math")
/ T Z& E/ Q1 @ [ol]它打印字符串"before functionA"。
9 `$ t6 g; Y0 \% y' ?# ]0 e1 }它执行def块,创建函数对象,然后将函数对象分配给一个名为 的变量functionA。9 O6 O* Y/ O4 l1 M# J# m
它打印字符串"before functionB"。
) k, X2 I2 ?) Z' r9 G' @; F2 A/ k" ]它执行第二个def块,创建另一个函数对象,然后分配给 变量functionB。
% X0 r9 j) a3 X( z8 h它打印字符串"before __name__ guard"。[/ol]只有当你的模块是主程序时( L, A: @9 C) M8 E
[ol]假如你的模块是主程序,它会看到的__name__确实设置为"__main__"并调用两个函数打印字符串"Function A"和"Function B 10.0".[/ol]只有当您的模块被另一个导入时) r( p0 ?( D* a+ v( t
[ol](相反)假如你的模块不是主程序,而是由另一个程序导入,那么__name__will "foo",not "__main__",它将跳过if句子的主体。[/ol]总是* V: c% E) g! r) c" L, l7 R
[ol]它会"after __name__ guard"在两种情况下打印字符串。[/ol]概括
, P z$ g' ?- C( n9 W$ t6 U总之,在两种情况下打印以下内容:. ^. }- `+ e! l. H. H
# 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
+ q& G) G4 Q0 P N 为什么这样工作?你自然会想知道为什么有人想要这个。嗯,有时候你想写一个。.py其他程序和/或模块都可以用作模块,也可以用作主程序本身。
/ j9 ^+ l- Q7 F$ m5 `/ f5 w您的模块是一个库,但您想要一个脚本模式,它运行一些单元测试或演示。
" E, h# _/ {0 X' U" Y您的模块仅用作主程序,但它有一些单元测试,通过导入测试框架.py脚本和其他文件并运行特殊的测试功能来工作。您不希望它尝试运行脚本,因为它正在导入模块。' {; x; P4 g# L
您的模块主要用作主程序,但也为高级用户提供了对程序员友好的 API。除此之外, Python 操作脚本只设置一些魔法变量并导入脚本,非常优雅。操作脚本是导入脚本模块的副作用。
+ E3 D4 Y: x+ b1 m% K( P问答问:我能有多个__name__答:这很奇怪,但语言不会阻止你。' m( t; d' ^, o% b0 ^/ h
假设以下内容是foo2.py. 如果你python foo2.py说命令行会发生什么?为什么?
' J1 R: [! k) W+ |1 \6 ]0 [+ n# 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"): W5 O4 T7 \7 e) a
现在,如果你取消取消了它__name__签入会发生什么?foo3.py:
H S; O7 U' X0 S5 j1 ?6 R5 V/ ?# 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")
5 M4 }# S9 P$ u8 @% N 当它被用作脚本时,它会做什么?导入模块时?
' W* _5 o. A; B/ z# Suppose this is in foo4.py__name__ = "__main__"def bar(): print("bar")print("before __name__ guard")if __name__ == "__main__": bar()print("after __name__ guard")
( s5 \+ g" i I/ t; `5 | Q7 G. `
|
|