遇到个小白常见的问题,发现度娘里面没有记录,翻墙谷歌了下,解决问题,在此写个说明。
事情起因:
在jupyter notebook中导入文件时发生了错误:
%load p2_test1.py错误信息:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py in find_user_code(self, target, raw, py_only, skip_encoding_cookie, search_ns)
   3586         try:                                              # User namespace
-> 3587             codeobj = eval(target, self.user_ns)
   3588         except Exception:
<string> in <module>
NameError: name 'p2_test1' is not defined
During handling of the above exception, another exception occurred:
ValueError                                Traceback (most recent call last)
<ipython-input-1-e4e531e2ca85> in <module>
----> 1 get_ipython().run_line_magic('load', 'p2_test1.py')
/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 
<decorator-gen-47> in load(self, arg_s)
/usr/local/lib/python3.5/dist-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):
/usr/local/lib/python3.5/dist-packages/IPython/core/magics/code.py in load(self, arg_s)
    333         search_ns = 'n' in opts
    334 
--> 335         contents = self.shell.find_user_code(args, search_ns=search_ns)
    336 
    337         if 's' in opts:
/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py in find_user_code(self, target, raw, py_only, skip_encoding_cookie, search_ns)
   3588         except Exception:
   3589             raise ValueError(("'%s' was not found in history, as a file, url, "
-> 3590                                 "nor in the user namespace.") % target)
   3591 
   3592         if isinstance(codeobj, str):
ValueError: 'p2_test1.py' was not found in history, as a file, url, nor in the user namespace.出现这个问题是因为解释器找不到对应的文件。念了“妈咪妈咪轰”pwd后,发现问题所在:
%pwd
llpwd显示当前目录不是该文件所在的目录。这下明白了,使用咒语要谨慎,记得在念“妈咪妈咪轰”load前,要cd到该文件的目录下去。
参考:
https://stackoverflow.com/questions/50658677/jupyter-notebook-nameerror-name-main-is-not-defined