问题描述
很难找到这个问题的标题,希望这个帖子不是重复的.
It is hard to find a title for this question and hopefully this thread is not a duplicate.
我正在用 Python 2.7(使用 PyCharm 2016.2.2)为一个项目编写长脚本,并决定将其拆分为不同的 .py 文件,然后我可以将其导入到主文件中.
I was writing that long script in Python 2.7 (using PyCharm 2016.2.2) for a project and decided to split it in different .py files which I could then import into a main file.
不幸的是,似乎在代码前面导入模块(例如 numpy)并不意味着下面导入的 .py 文件会知道这一点.
Unfortunately, it seems that when importing a module (e.g. numpy) earlier in the code does not mean that the .py files that are imported below will have knowledge of that.
我是 python 的新手,我想知道是否有一种简单的解决方法.
I am new to python and I was wondering whether there is an easy workaround for that one.
为了更清楚,这是我的代码的示例结构:
To be more clear, here is an example structure of my code:
Main.py(用于运行脚本的文件):
Main.py (the file that is used to run the script):
import basic
numpy.random.seed(7)
import load_data
basic.py:
import pandas
import numpy
etc...
load_data.py:
raw_input = pandas.read_excel('April.xls', index_col = 'DateTime')
etc...
Main.py的第二行会报错"NameError: name 'numpy' is not defined",意思是中导入的numpybasic.py 不会传递给 Main.py.
The second line of Main.py would cause an error "NameError: name 'numpy' is not defined", meaning the numpy that was imported in basic.py is not passed to the Main.py.
我猜 load_data.py 中的代码会发生类似的错误,因为 'pandas' 不是一个定义的名称.
I guess that a similar error would occur for the code in load_data.py since 'pandas' would not be a defined name.
有什么想法吗?
谢谢.
推荐答案
basic.py
中导入的 numpy
模块有一个仅在 basic 中定义的引用.py
范围.您必须在任何使用它的地方显式导入 numpy
.
The numpy
module imported in basic.py
has a reference defined only withing basic.py
scope. You have to explictly import numpy
everywhere you use it.
import basic.py
import numpy
numpy.random.seed(7)
import load_data.py
这篇关于NameError -- 当脚本在多个 python 文件中分解时导入的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!