[英]how to stop the import of a python module
suppose I have a file my_plugin.py
假设我有一个文件
my_plugin.py
var1 = 1
def my_function():
print("something")
and in my main program I import this plugin 在我的主程序中,我导入了此插件
import my_plugin
Is there a way to silently disable this plugin with something like a return statement? 有没有办法像return语句那样静默禁用此插件?
for example I could "mask" the behavior of my_function
like this: 例如,我可以像这样“屏蔽”
my_function
的行为:
def my_function():
return
print("something")
I am wondering if I can do this for the module as a way to turn it on and off depending on what I am trying to do with the overall project. 我想知道是否可以针对模块执行此操作,以根据我要对整个项目进行的操作来打开和关闭该模块。 So something like:
所以像这样:
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")
I suppose I could just comment everything out and that would work... but I was wondering if something a little more concise exists 我想我可以将所有内容都注释掉,并且行得通...但是我想知道是否存在一些更简洁的方法
--- The purpose: The thinking behind this is I have a large-ish code-base that is extensible by plugins. ---目的:背后的想法是我有一个很大的代码库,可以通过插件扩展。 There is a plugins directory so the main program looks in the directory and runs all the modules that are in there.
有一个插件目录,因此主程序在目录中查找并运行其中的所有模块。 The use case was just to put a little kill switch inside plugins that are causing problems as an alternative to deleting or moving the file temporarily
用例只是在引起问题的插件中放置一个小小的kill开关,以作为临时删除或移动文件的替代方法
You can just conditionally import the module: 您可以有条件地导入模块:
if thing == otherthing:
import module
This is entire valid syntax in python. 这是python中的完整有效语法。 With this you can set a flag on a variable at the start of your project that will import modules based on what you need in that project.
这样,您可以在项目开始时在变量上设置标志,该标志将根据您在该项目中需要的内容导入模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.