打包Python代码后的NameError

时间:2016-07-02 10:51:27

标签: python python-module

我一直在使用IPython,而无需打包代码。我浏览了以下几页并为我的模块设置了目录结构,现在使用IPython来启动程序。

https://docs.python.org/3/reference/import.html

https://docs.python.org/3/tutorial/modules.html

http://pythoncentral.io/how-to-create-a-python-package/

以下是我的设置要点

root foder

  1. 模块(目录)

    1.1 external.py

    1.2 getdata.py

  2. driver.ipynb

  3. 我创建了一个名为modules的目录并创建了两个文件。

    模块(目录)

    - external.py(包含以下内容)

    import glob # and many other import statements
    

    - getdata.py(包含以下内容)

    def funcname():
        file_list = glob.glob("Data/")
    
    def other_func():
        x = x + 3
    

    现在我在IPython笔记本中运行以下代码

    from modules import external
    from modules.getdata import * 
    # so that I can funcname() instead of modules.getdata.funcname()
    
    other_func() # runs as expected
    funcname() # NameError global name 'glob' is not defined
    

    在IPython笔记本中运行 glob.glob(" Data /")不会发出任何错误。

    如何在不重命名任何功能的情况下解决此命名空间问题?我有十几个功能,他们都有同样的问题。

    编辑1: - 我忘记提及 我已经尝试过的东西

    getdata.py中的import语句

    import glob
    def funcname():
        file_list = glob.glob("Data/")
    
    def other_func():
        x = x + 3
    

    我有多个使用glob的文件。除了在每个文件中导入模块之外,还有其他更好的选择吗?

1 个答案:

答案 0 :(得分:1)

import glob使用getdata.py模块)中添加glob,而不是external.py

import glob  # <--

def funcname():
    file_list = glob.glob("Data/")

def other_func():
    x = x + 3
相关问题