如何让自编模块所在的目录加入到python的搜索路径里:
使用
import sys
查看路径
sys.path
把*.py放入对应的路径中!
Out[30]:
['',
'C:\\ProgramData\\Anaconda3\\python36.zip',
'C:\\ProgramData\\Anaconda3\\DLLs',
'C:\\ProgramData\\Anaconda3\\lib',
'C:\\ProgramData\\Anaconda3',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\Administrator\\.ipython']
*因为导入操作都是执行同样的命令: import hello,只是因为其路径不在pythonpath的名单里, 所以会抛出:
ModuleNotFoundError: No module named 'hello'
解决办法(转载):
假设: myudf.py所在的路径为: c:\abc\xyz
方法1: 用Sypder工具:
Tools/PYTHONPATH manager: to open a window
Add and Select the target path to PYTHONPYTH
then 同步(spyder与python的路径同步)
then OK to close this dialog window
then open a new Ipython console,
with in it, I can import myudf without error.
方法2: 写脚本
该方法未经本人亲测. 是网摘过来的, 相信也能成功的.
import sys
sys.path.append("folder_containing_my_python_util_script")
import my_util
确认标的目录是否加入了"搜索路径列表"
在新的IPython窗口里输入: sys.path 得到:
sys.path
Out[9]:
['',
'd:\\Anaconda2\\lib\\site-packages\\pybacktest-0.1-py2.7.egg',
'C:\\Documents and Settings\\Administrator\\duanqs\\script',
'D:\\DB\\myutil',
'd:\\Anaconda2\\python27.zip',
'd:\\Anaconda2\\DLLs',
'd:\\Anaconda2\\lib',
'd:\\Anaconda2\\lib\\plat-win',
'd:\\Anaconda2\\lib\\lib-tk',
'd:\\Anaconda2',
'd:\\anaconda2\\lib\\site-packages\\sphinx-1.3.5-py2.7.egg',
'd:\\anaconda2\\lib\\site-packages\\setuptools-20.3-py2.7.egg',
'd:\\Anaconda2\\lib\\site-packages',
'd:\\Anaconda2\\lib\\site-packages\\win32',
'd:\\Anaconda2\\lib\\site-packages\\win32\\lib',
'd:\\Anaconda2\\lib\\site-packages\\Pythonwin',
'd:\\Anaconda2\\lib\\site-packages\\IPython\\extensions',
'C:\\Documents and Settings\\Administrator\\.ipython']
在旧的IPython控制台里的查看结果:
sys.path
Out[125]:
['',
'd:\\Anaconda2\\lib\\site-packages\\pybacktest-0.1-py2.7.egg',
'D:\\DB\\myutil',
'd:\\Anaconda2\\python27.zip',
'd:\\Anaconda2\\DLLs',
'd:\\Anaconda2\\lib',
'd:\\Anaconda2\\lib\\plat-win',
'd:\\Anaconda2\\lib\\lib-tk',
'd:\\Anaconda2',
'd:\\anaconda2\\lib\\site-packages\\sphinx-1.3.5-py2.7.egg',
'd:\\anaconda2\\lib\\site-packages\\setuptools-20.3-py2.7.egg',
'd:\\Anaconda2\\lib\\site-packages',
'd:\\Anaconda2\\lib\\site-packages\\win32',
'd:\\Anaconda2\\lib\\site-packages\\win32\\lib',
'd:\\Anaconda2\\lib\\site-packages\\Pythonwin',
'd:\\Anaconda2\\lib\\site-packages\\IPython\\extensions',
'C:\\Documents and Settings\\Administrator\\.ipython']
对比后, 发现第二行处的目录:
'C:\Documents and Settings\Administrator\duanqs\script'
就是新加入的目录.
然也!!!!!