繁体   English   中英

如何从子函数将模块导入main()?

[英]How can I import a module into main() from a sub function?

在Python脚本中,我想控制模块从子函数到main()的导入。 这可能吗? 怎么样?

原因:我有一个子函数来处理命令行参数(使用argparse),并希望基于用户输入导入模块。 具体来说,我想让用户指定matplotlib的后端,必须在导入matplotlib.pylab之前对其进行设置。 但是,我认为这个问题具有更广泛的用途。

这是一个代码片段:

def main():

    args = handleCommandLine();

    fig, ax = plt.subplots(1)   # ERROR: plt not defined

    # Snip ...


def handleCommandLine():
    p = argparse.ArgumentParser()
    p.add_argument('--backend', '-b', default=None, help='Specify plotting backend')
    args = p.parse_args()

    if args.backend != None:
        matplotlib.use(args.backend)  #Must occur before importing pyplot

    import matplotlib.pyplot as plt   #Must occur after setting backend, if desired
    return args

如果您希望它的行为就像您在模块顶部的import matplotlib.pyplot as plt一样执行import matplotlib.pyplot as plt ,即使您没有这样做,也可以使用全局变量:

def handleCommandLine():
    p = argparse.ArgumentParser()
    p.add_argument('--backend', '-b', default=None, help='Specify plotting backend')
    args = p.parse_args()

    if args.backend != None:
        matplotlib.use(args.backend)  #Must occur before importing pyplot

    global plt  #Style choice: Can also be placed at the top of the function
    import matplotlib.pyplot as plt  #Must occur after setting backend
    return args

否则,可以像处理任何其他变量一样,通过函数返回传递包含的库引用:

def main():
    plt, args = handleCommandLine()   # CHANGED HERE
    fig, ax = plt.subplots(1)
    # ...    

def handleCommandLine():
    p = argparse.ArgumentParser()
    p.add_argument('--backend', '-b', default=None, help='Specify plotting backend')
    args = p.parse_args()

    if args.backend != None:
        matplotlib.use(args.backend)  #Must occur before importing pyplot

    import matplotlib.pyplot as plt   #Must occur after setting backend, if desired
    return plt, args   # CHANGED HERE

import语句非常类似于赋值-除非您显式声明为global ,否则它将分配给本地名称。 以下进口plt到全局命名空间:

def handleCommandLine():
    global plt
    ...
    import matplotlib.pyplot as plt

你不能

我可以通过从handleCommandLine返回plt或将导入移动到main来解决此问题。

global plt放在handleCommandLine()的开头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM