简体   繁体   English

如何从目录导入模块?

[英]How to import a module from a directory?

On my system I have two versions of Python (to call them I type python and python2 in the command line). 在我的系统上,我有两个版本的Python(称之为我在命令行中键入pythonpython2 )。 When I use the first version of Python, I cannot import sklearn module but I can do it in the second version of Python. 当我使用Python的第一个版本时,我无法导入sklearn模块,但我可以在第二个版本的Python中执行。

I would like to use the first version of python (because other modules are available there) and, at the same time, I would like to be able to import sklearn from this version of Python. 我想使用第一个版本的python(因为其他模块在那里可用),同时,我希望能够从这个版本的Python import sklearn

My solution was to use: 我的解决方案是使用:

import sys
sys.path.append('location_of_the_sklearn_module')

To find the location of the sklearn module I started a python session (using the second version of python, in which sklearn works). 为了找到sklearn模块的位置,我启动了一个python会话(使用第二个版本的python,其中sklearn工作)。 The I type: 我输入:

import sklearn
sklearn.__file__

As a result I got: 结果我得到了:

/home/name/my_name/numpy/local/lib/python2.7/site-packages/sklearn/__init__.pyc

In the session of the first version of Python I tried: 在Python的第一个版本的会话中,我试过:

import sys
sys.path.append('/home/name/my_name/numpy/local/lib/python2.7/site-packages/sklearn')
import sklearn

Unfortunately it did not work. 不幸的是它没有用。 As a result I got: ImportError: No module named sklearn 结果我得到: ImportError: No module named sklearn

Does anybody know what I am doing wrong and if it is possible to reach the goal in the way I try? 有人知道我做错了什么,是否有可能以我尝试的方式达到目标?

When importing packages, you need to add the parent directory of the package to PYTHONPATH , not the package directory itself, so just change... 导入包时,需要将包的父目录添加到PYTHONPATH ,而不是包目录本身,所以只需更改...

sys.path.append('/home/name/my_name/numpy/local/lib/python2.7/site-packages/sklearn')

...to... ...至...

sys.path.append('/home/name/my_name/numpy/local/lib/python2.7/site-packages')

...although it may not necessarily import correctly in Python 3.x. ...虽然它可能不一定在Python 3.x中正确导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM