我需要从另一个运行代码的Python文件中仅导入单个函数,但是当我导入该函数时,它会运行整个代码而不是只导入我想要的函数。 有没有办法从另一个.py文件中仅导入单个函数而不运行整个代码?
我需要从另一个运行代码的Python文件中仅导入单个函数,但是当我导入该函数时,它会运行整个代码而不是只导入我想要的函数。 有没有办法从另一个.py文件中仅导入单个函数而不运行整个代码?
another.py
中,将你不想运行的代码移到一个只有在脚本被明确调用运行而不是仅仅被导入时才运行的块中。def my_func(x):
return x
if __name__ == '__main__':
# Put that needs to run here
现在,如果你在your_script.py
中,你可以导入another
模块而不会运行my_func
函数。
from another import my_func # Importing won't run the function.
my_func(...) # You can run the function by explicitly calling it.
if '__main__' == __name__:
只有在将该python文件作为脚本运行时,__name__
变量才会是__main__
。当您导入该脚本时,该条件语句内的任何代码都不会运行。
def print_one():
print "one"
def print_two():
print "two"
def what_i_really_want_import():
print "this is what I wanted"
if __name__ == '__main__':
print_one()
print_two()
print "one"
print "two"
def what_i_really_want_import():
print "this is what I wanted"
在一个函数中使用main guard可以防止其在导入时被执行,尽管如果需要仍然可以调用它。如果name == "main",这实际上意味着“我是否从命令行运行此脚本?”在导入时,if条件将返回false,因此不会发生print_one()和print_two()的调用。
保留某些内容在导入时执行也有一些好处。其中一些是常量、初始化/配置步骤,您希望自动执行。同时,在模块级别设置变量是实现单例的一种优雅方式。
def print_one():
print "one"
def print_two():
print "two"
time_when_loaded = time.time()
class MySingleton(object):
pass
THE_ANSWER = 42
singleton = MySingleton()
总的来说,不要在加载时留下太多需要执行的代码,否则你就会遇到这些问题。
# How to makes a module without being fully executed ?!
# You need to follow below structure
"""
def main():
# Put all your code you need to execute directly when this script run directly.
pass
if __name__ == '__main__':
main()
else:
# Put functions you need to be executed only whenever imported
"""
1. 在编辑器中打开 2. 查找定义 3. 以老式方式复制粘贴
有时候,最简单的解决方案也是最不干净的。