导入python模块而不运行它

Me *_*Man 11 python module function python-import

我需要从另一个运行其中的东西的python文件中导入一个函数,但是当我导入函数时,它运行整个代码而不是只导入我想要的函数.反正只有从另一个.py文件导入一个函数而不运行整个代码?

bak*_*kal 17

another.py,将您不想运行的代码移动到仅在显式调用脚本运行而不是仅导入的情况下运行的块

def my_func(x):
    return x

if __name__ == '__main__':
    # Put that needs to run here
Run Code Online (Sandbox Code Playgroud)

现在,如果你在your_script.py,你可以导入它,它将无法运行

from another import my_func # Importing won't run the function.
my_func(...) # You can run the function by explicitly calling it.
Run Code Online (Sandbox Code Playgroud)


Ana*_*mar 5

在您要导入的另一个 python 脚本中,您应该将运行脚本时需要执行的所有代码放入以下 ​​if 块中 -

if '__main__' == __name__:
Run Code Online (Sandbox Code Playgroud)

仅当将该 python 文件作为脚本运行时,__name__变量将为__main__. 导入脚本时,此 if 条件内的任何代码都不会运行。