代码之家  ›  专栏  ›  技术社区  ›  Vince W.

如何停止导入python模块

  •  0
  • Vince W.  · 技术社区  · 6 年前

    假如我有档案 my_plugin.py

    var1 = 1
    def my_function():
        print("something")
    

    在我的主程序中,我导入这个插件

    import my_plugin
    

    有没有一种方法可以用类似于返回语句的东西静默地禁用这个插件?

    例如,我可以“掩盖” my_function 这样地:

    def my_function():
        return
        print("something")
    

    我想知道我是否可以为模块这样做,作为打开和关闭它的一种方式,这取决于我试图对整个项目做什么。比如:

    return  # this is invalid, but something that says stop running this module
            # but continue on with the rest of the python program
    var1 = 1
    def my_function():
        print("something")
    

    我想我可以把每件事都说出来,这样就行了……但我想知道是否存在一些更简洁的东西

    ——目的: 这背后的想法是,我有一个大型的ISH代码库,可以通过插件进行扩展。有一个插件目录,所以主程序在该目录中查找并运行其中的所有模块。这个用例只是在插件中放置一个小的kill开关,作为临时删除或移动文件的替代方法,这个开关会导致一些问题。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Ryan Schaefer    6 年前

    您可以有条件地导入模块:

    if thing == otherthing:
       import module
    

    这是Python中的完整有效语法。通过这个,您可以在项目开始时为变量设置一个标志,该标志将根据您在该项目中需要的内容导入模块。