从其他包中导入Python模块 [英] Python import modules from other packages

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

问题描述

默认情况下,Python将在lib/python2.7/site-packages中寻找模块 但是我现在正试图从HPCC上的其他目录中导入软件包,这是我必须依靠的,因为我没有root访问权,因此很难自行安装.

Python will by default be looking for modules from lib/python2.7/site-packages But I'm now trying to import packages from other directories on HPCC, which I have to rely on, because I've no root access, it'll be difficult to install myself.

但是我的问题是:如何从其他目录导入模块?

But my question is: how to import modules from other directories?

我尝试过:

export PYTHONPATH="/path/to/import/modules:$PYTHONPATH"

但是它不起作用. 我该怎么办? 谢谢

But it's not working. What should I do? Thanks

=======================================

=========================================

我要使用的python是2.7.9,所以我已经在.bash_profile中设置了:

My python to use is 2.7.9 ,so I've already set in .bash_profile:

export PATH="/share/pkg/python/2.7.9/bin:$PATH"

2.7.9_packages是包含我想要的模块的目录(您可以看到那些文件夹)

2.7.9_packages is the directories containing modules(you could see those folders) I want:

,但是您会看到2.7.9_packages2.7.9在同一路径下.

but you could see 2.7.9_packages and 2.7.9 are under the same path.

推荐答案

在何处放置您自己的模块:-

Where to place your own modules:-

  1. 将模块放置在python通常会搜索的目录之一中
  2. 将所有模块与程序放在同一目录中
  3. 创建一个目录/目录来保存您的模块并修改sys.path

我确定第三个选项正是您要寻找的

I am sure the third option is exactly what your looking for

您可以通过多种方式修改sys.path

You can modify sys.path in various ways

  • 程序代码中的硬编码PYTHONPATH环境变量
  • 使用.pth方法

  • Hardcode PYTHONPATH environment variable in your program code
  • Using .pth method

创建一个新文件,例如myModules.pth并将其放置在Windows上sys.prefix指定的路径中,myModules.pth的内容可以为

Create a new file eg myModules.pth and place it in path specified by sys.prefix on windows the content of myModules.pth can be

c:\ My Documents \ python \ modules

c:\My Documents\python\modules

这意味着您可以为要导入的特定模块放置路径

That means you can place your path for that specific module you want to import there

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

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