从python中的另一个目录导入包和模块 [英] importing package and modules from another directory in python

查看:813
本文介绍了从python中的另一个目录导入包和模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在路径中有一堆python脚本

I have a bunch of python scripts in the path

/home/yotam/Applications/pyFoo

其中一个是__init__.py,据我所知,它将pyFoo文件夹变成了一个包.该文件夹还具有一个src子文件夹,该子文件夹存储自己的__init__.py文件以及一些其他有用的脚本.

one of them is __init__.py which, to my understanding, turns the pyFoo folder into a package. The folder also has a src subfolder, which stores an __init__.py file of its own, as well as some other helpful scripts.

我想导入一个名为Bar.py的文件(模块?),该文件使用来自/home/yotam/Applications/pyFoo/src的脚本.如果我尝试从python解释器加载它,则使用

I want to import one of the files (modules?), called Bar.py, that uses scripts from /home/yotam/Applications/pyFoo/src. If I try to load it from the python interpreter, while in the folder ''/home/yotam/Applications'' using

>>> from pyFoo import Bar as B

一切都很好.但是,如果我想从其他文件夹中运行它,例如我的主目录,出现错误

everything is fine. If, however I want to run it from other folders, e.g. my home directory, I get the error

ValueError: Attempted relative import in non-package

如何从计算机上的任何位置导入Bar.py?

How can I import Bar.py from anyplace on my machine?

推荐答案

只需将目录添加到您的sys.path:

Just add the directory to your sys.path:

import sys
sys.path.append( '/path/to/libs' )

import my_lib_in_another_dir

这篇关于从python中的另一个目录导入包和模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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