导入一个python模块而不运行它 [英] Import a python module without running it

查看:123
本文介绍了导入一个python模块而不运行它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

another.py ,将不想被运行的代码移入只在脚本被显式调用运行时才运行的代码块,而不仅仅是导入

  def my_func(x):
return x

if __name__ =='__main__':
#把这个需要运行在这里

现在如果你在 your_script.py ,你可以导入它,并且它不会运行从另一个import my_func
运行

  my_func(...)


I need to import only a single function from another python file which runs stuff in it, but when I import the function, it runs the entire code instead of importing just the function I want. Is there anyway to only import a single function from another .py file without running the entire code?

解决方案

In another.py, move the code that you don't want to be ran into a block that only runs when the script is explicitly called to run and not just imported

def my_func(x):
    return x

if __name__ == '__main__':
    # Put that needs to run here

Now if you are in your_script.py, you can import it, and it won't run

from another import my_func
my_func(...)

这篇关于导入一个python模块而不运行它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆