导入python模块不在路径上 [英] Import python module NOT on path

查看:580
本文介绍了导入python模块不在路径上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块foo,包含util.py和bar.py。

I have a module foo, containing util.py and bar.py.

我想在IDLE或python会话中导入它。我该怎么做?

I want to import it in IDLE or python session. How do I go about this?

我找不到关于如何导入不在当前目录或默认python PATH中的模块的文档。
尝试<&c; c>导入<完整路径> /foo/util.py,
从< full路径>中import util

I could find no documentation on how to import modules not in the current directory or the default python PATH. After trying import "<full path>/foo/util.py", and from "<full path>" import util

我能得到的最接近的是

import imp
imp.load_source('foo.util','C:/.../dir/dir2/foo')

这让我在Windows 7上拒绝了权限。

Which gave me Permission denied on windows 7.

推荐答案

单向只是修改你的路径

import sys
sys.path.append('C:/full/path')
from foo import util,bar

注意这需要foo成为python包,即包含 __ init __。py 文件。如果您不想修改 sys.path ,则可以还修改 PYTHONPATH 环境变量在您的系统上安装模块。请注意,这意味着该目录中的其他目录或 .py 文件可能会被无意中加载。

Note that this requires foo to be a python package, i.e. contain a __init__.py file. If you don't want to modify sys.path, you can also modify the PYTHONPATH environment variable or install the module on your system. Beware that this means that other directories or .py files in that directory may be loaded inadvertently.

因此,您可能想使用 imp.load_source 而不是。它需要文件名,而不是目录(允许当前用户读取的文件):

Therefore, you may want to use imp.load_source instead. It needs the filename, not a directory (to a file which the current user is allowed to read):

import imp
util = imp.load_source('util', 'C:/full/path/foo/util.py')

这篇关于导入python模块不在路径上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆