Python 模块中的条件导入

Python 模块中的条件导入,python,matplotlib,Python,Matplotlib,我已经创建了一个模块modA,我正在我的主程序中导入它。根据主程序中发生的情况(它有一个交互模式和一个批处理脚本模式),我希望modA本身使用TkAgg后端或ps后端导入matplotlib。我的主程序有没有办法将信息传递给modA,告诉它应该如何导入matplotlib 为澄清情况: 主要节目: #if we are in interactive mode #import modA which imports matplotlib using TkAgg backend #else #impo

我已经创建了一个模块modA,我正在我的主程序中导入它。根据主程序中发生的情况(它有一个交互模式和一个批处理脚本模式),我希望modA本身使用TkAgg后端或ps后端导入matplotlib。我的主程序有没有办法将信息传递给modA,告诉它应该如何导入matplotlib

为澄清情况:

主要节目:

#if we are in interactive mode
#import modA which imports matplotlib using TkAgg backend
#else
#import modA which imports matplotlib using the ps backend
模块modA:

#import matplotlib
#matplotlib.use('ps') or matplotlib.use('TkAgg') (how can I do this?)

在您的模块中有一个函数将决定这一点

import matplotlib

def setEnv(env):
    matplotlib.use(env)
然后在您的程序中,您可以有
modA.setEnv('ps')
或基于if-else语句条件的其他内容

此处不需要条件导入(因为您只使用一个外部模块),但可以这样做:

if condition:
    import matplotlib as mlib
else:
    import modifiedmatplotlib as mlib
有关在函数中导入模块的更多信息,请参见以下内容:


您可以通过评估传递给命令行的参数来检测会话的启动方式:

import sys
import matplotlib

if '-i' in sys.argv:
    # program started with an interactive session
    matplotlib.use('TkAdd')
else:
    # batch session
    matplotlib.use('ps')
如果没有,您可以使用os.environ在模块之间进行通信:

大体上:

import os
if interactive:
    os.environ['MATPLOTLIB_USE'] = 'TkAdd'
else:
    os.environ['MATPLOTLIB_USE'] = 'ps'
在modA中:

import os
import matplotlib
matplotlib.use(os.environ['MATPLOTLIB_USE'])

是否可以以两种不同的名称导入两次类似matplotlib的模块,即将matplotlib导入为matplotlib1,将matplotlib导入为matplotlib2,然后根据需要使用其中一种或另一种?这是一个很好的建议,但也有一个复杂之处:一旦导入matplotlib,然后通过该函数调用matplotlib.use(),我仍然想导入matplotlib.pyplot(导入matplotlib和matplotlib.use()实际上是某种初始化。有什么方法可以解决这个问题吗?到底是什么阻止您单独导入matplotlib.pyplot?因为单独导入matplotlib.pyplot将使用默认后端,并且(我可能在这里错了)似乎以编程方式设置后端的唯一方法是首先导入matplotlib并调用matplotlib。使用('desired_backend')啊,好吧,在该函数中的
use()
之后导入它。@user3208430只需将其指定为
global
,它将始终可用。请参阅此处的详细信息: