Python 如果“你的名字”是什么意思__主要内容:做
给定以下代码,如果uuu name uuu==“uuuu main uuu”:做什么Python 如果“你的名字”是什么意思__主要内容:做,python,namespaces,main,python-module,idioms,Python,Namespaces,Main,Python Module,Idioms,给定以下代码,如果uuu name uuu==“uuuu main uuu”:做什么 # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while True: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleepti
# Threading example
import time, thread
def 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))
如果使用类似python myscript.py的命令从(比如)命令行运行脚本时,脚本运行的部分是
名称
简短回答
# Suppose this is foo.py.
print("before import")
import math
print("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")
这是一个样板代码,可以防止用户无意中调用脚本。以下是脚本中省略保护时的一些常见问题:
- 如果在另一个脚本中导入无担保脚本(例如,
),则第二个脚本将触发第一个脚本在导入时运行,并使用第二个脚本的命令行参数。这几乎总是一个错误导入不带\u a\u name\u eq\u main\u guard的my\u script\u
- 如果在无担保脚本中有一个自定义类并将其保存到pickle文件中,则在另一个脚本中取消对其的pickle将触发无担保脚本的导入,问题与上一个项目符号中概述的相同
- 它设置一些特殊变量,如
,然后\uuuuu name\uuuuu
- 它执行文件中找到的所有代码
\uuuu name\uuuu
检查的问题的关系
代码示例
让我们使用稍微不同的代码示例来探索导入和脚本是如何工作的。假设以下内容位于名为foo.py
的文件中
# Suppose this is foo.py.
print("before import")
import math
print("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")
特殊变量
当Python解释器读取源文件时,它首先定义几个特殊变量。在本例中,我们关心\uuu name\uu
变量
当您的模块是主程序时
如果您将模块(源文件)作为主程序运行,例如
python foo.py
解释器将硬编码字符串“\uuuuu main\uuuuuu”
分配给\uuuuu name\uuuuuuu
变量,即
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"
# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
当您的模块被其他模块导入时
另一方面,假设其他模块是主程序,它导入您的模块。这意味着在主程序或主程序导入的其他模块中有这样的语句:
# Suppose this is in some other main program.
import foo
解释器将搜索您的foo.py
文件(同时搜索一些其他变量),在执行该模块之前,解释器将把import语句中的名称“foo”
分配给\u name\u
变量,即
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"
# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
执行模块的代码
设置特殊变量后,解释器执行模块中的所有代码,每次执行一条语句。您可能希望在代码示例旁边打开另一个窗口,以便按照此说明进行操作
始终
”
(不带引号)
math
模块并将其分配给名为math
的变量。这相当于将import math
替换为以下内容(请注意,\uuuuuu import\uuuuu
是Python中的一个低级函数,它接受字符串并触发实际导入):
def
块,创建函数对象,然后将该函数对象分配给名为function
的变量
def
块,创建另一个函数对象,然后将其分配给名为functionB
的变量
\uuuu name\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
\uuuu name\uuuuuuuuu
将是“foo”
,而不是“\uuuuu main\uuuuuuuuuu”
,如果语句,它将跳过的主体
#如果foo是主程序,会打印什么
进口前
功能前
职能B之前
在u u name _;警卫之前
功能A
功能B10.0
在“姓名”之后
#如果foo作为常规模块导入,将打印什么
进口前
功能前
职能B之前
在u u name _;警卫之前
在“姓名”之后
为什么会这样?
你可能很自然地想知道为什么有人会想要这个。有时,您需要编写一个.py
文件,该文件既可以被其他程序和/或模块用作模块,也可以作为主程序本身运行。示例:
- 您的模块是一个库,但您希望有一个脚本模式,在该模式下运行一些单元测试或演示
- 您的模块仅用作主程序,但它有一些单元测试,测试框架通过导入脚本之类的
文件并运行特殊的测试函数来工作。您不希望它仅仅因为正在导入模块而尝试运行脚本.py
- 您的模块主要用作主程序,但它也提供了一个程序员fr
# file one.py def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module")
# file two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module")
python one.py
top-level in one.py one.py is being run directly
python two.py
top-level in one.py one.py is being imported into another module top-level in two.py func() in one.py two.py is being run directly
# a.py import b
# b.py print "Hello World from %s!" % __name__ if __name__ == '__main__': print "Hello World again from %s!" % __name__
$ python a.py Hello World from b!
$ python b.py Hello World from __main__! Hello World again from __main__!
def some_function_for_instance_main(): dosomething() __name__ == '__main__' and some_function_for_instance_main()
def do_important(): """This function does something very important"""
do_important()
~$ python important.py
import important
# do_important() # I must remember to uncomment to execute this!
if __name__ == "__main__": do_important()
def main(): """business logic for when running this module as the primary one!""" setup() foo = do_important() bar = do_even_more_important(foo) for baz in bar: do_super_important(baz) teardown() # Here's our payoff idiom! if __name__ == '__main__': main()
import important important.main()
if __name__ == '__main__': main()
if __name__ == '__main__': # Do something appropriate here, like calling a # main() function defined elsewhere in this module. main() else: # Do nothing. This module has been imported by another # module that wants to make use of the functions, # classes and other useful bits it has defined.
python mycode.py
if __name__ == '__main__': main()
import mycode # ... any amount of other code mycode.main()
... <Block A> if __name__ == '__main__': <Block B> ...
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))
lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
if __name__ == "__main__": # Execute only if run as a script main()
print __name__
if __name__ == "__main__": print "direct method"
def a(): print('A function in ab file'); a()
import ab def main(): print('main function: this is where the action is') def x(): print ('peripheral task: might be useful in other projects') x() if __name__ == "__main__": main()
#script1.py print "Script 1's name: {}".format(__name__)
#script2.py import script1 print "Script 2's name: {}".format(__name__)
Script 1's name: __main__
Script1's name is script1 Script 2's name: __main__
# Other modules can IMPORT this MODULE to use the function fib def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() # This allows the file to be used as a SCRIPT if __name__ == "__main__": import sys fib(int(sys.argv[1]))
if __name__ == "__main__": main()
if __name__ == "__main__": main()
print(__name__) # It will print out __main__
import a # Prints a
# Code to be run when imported into another python file if __name__ == '__main__': # Code to be run only when run directly
>>> print(__name__) __main__ >>>
print(__name__)
def somefunction(): print(__name__)
import somefile somefile.somefunction()
>>> __name__ = 'Horrify' # Change default from __main__ >>> if __name__ == 'Horrify': print(__name__) ... >>> else: print('Not Horrify') ... Horrify >>>
if __name__ != '__main__': # Do some useful things
if __name__ == '__main__': # Execute something else: # Do some useful things
# test.py def test(): print('test module name=%s' %(__name__)) if __name__ == '__main__': print('call test()') test()
call test() test module name=__main__
#Script test.py apple = 42 def hello_world(): print("I am inside hello_world") if __name__ == "__main__": print("Value of __name__ is: ", __name__) print("Going to call hello_world") hello_world()
python test.py
Value of __name__ is: __main__ Going to call hello_world I am inside hello_world
#script external_calling.py import test print(test.apple) test.hello_world() print(test.__name__)
python external_calling.py
42 I am inside hello_world test
def a(): print("a") def b(): print("b") if __name__ == "__main__": print ("you can see me" ) a() else: print ("You can't see me") b()
# my_test_module.py print('This is going to be printed out, no matter what') if __name__ == '__main__': print('This is going to be printed out, only if user invokes the module as a script')
# main.py import my_test_module if __name__ == '__main__': print('Hello from main.py')
python main.py >> 'This is going to be printed out, no matter what' >> 'Hello from main.py'
python my_test_module.py >>> 'This is going to be printed out, no matter what' >>> 'This is going to be printed out, only if user invokes the module as a script'