导入Python模块但不执行它

15

我需要从另一个运行代码的Python文件中仅导入单个函数,但是当我导入该函数时,它会运行整个代码而不是只导入我想要的函数。 有没有办法从另一个.py文件中仅导入单个函数而不运行整个代码?


2
@Edd:可能不是重复的问题;如果你尝试导入的模块在导入时运行了你不想要的东西,那个问题中没有涉及到如何阻止它的内容。 - user2357112
@user2357112 哦,是的。我没有考虑到可能缺少“__main__”检查。抱歉! - Edd
5个回答

28
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.

5
在另一个需要导入的Python脚本中,您应该将所有需要在运行脚本时执行的代码放在以下if块内 -
if '__main__' == __name__:

只有在将该python文件作为脚本运行时,__name__变量才会是__main__。当您导入该脚本时,该条件语句内的任何代码都不会运行。


4
你可以将该函数移动到另一个文件中,并将其导入到你的文件中。
但是,你在导入时运行所有内容的事实让我想到,你需要将大部分导入模块中的内容移动到函数中,并在需要时使用主要保护调用它们。
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()

总的来说,不要在加载时留下太多需要执行的代码,否则你就会遇到这些问题。


1
# 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
"""

-12

1. 在编辑器中打开 2. 查找定义 3. 以老式方式复制粘贴

有时候,最简单的解决方案也是最不干净的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接