问题
It is hard to find a title for this question and hopefully this thread is not a duplicate.
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.
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.
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 (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...
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.
I guess that a similar error would occur for the code in load_data.py since 'pandas' would not be a defined name.
Any ideas?
Thanks.
回答1:
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
来源:https://stackoverflow.com/questions/39335948/nameerror-imported-modules-when-script-is-broken-down-in-multiple-python-file