添加到python路径mac os x

2024-04-25 13:04:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我以为

import sys
sys.path.append("/home/me/mydir")

在我的pythonpath后面附加一个dir

如果我打印sys.path,我的目录就在里面。

然后我打开一个新命令,它就不在了。

但不知怎的,Python无法导入我保存在那个目录中的模块。

我做错什么了?

我读过了。profile或.bash_profile就可以了。

我需要补充:

PATH="/Me//Documents/mydir:$PYTHONPATH"
export PATH

让它工作?


Tags: 模块pathimport命令目录bashhomedir
3条回答

Mathew的答案适用于终端python shell,但在我的例子中,它不适用于空闲shell,因为在我用Python2.7.7替换所有版本之前,已经存在许多版本的python。 我是如何用懒散来解决这个问题的。

  1. 在终端,cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. 然后sudo nano idlemain.py,如果需要,请输入密码。
  3. os.chdir(os.path.expanduser('~/Documents'))这一行之后,我添加了sys.path.append("/Users/admin/Downloads....")注意:用要添加python模块的目录替换引号的内容
  4. 要保存更改,请按ctrl+x并输入 现在打开idle并尝试导入python模块,对我来说没有错误!!!

不知道为什么Matthew的解决方案对我不起作用(可能是我正在使用OSX10.8,或者可能与macports有关)。但我在文件末尾添加了以下内容~/.profile

export PYTHONPATH=/path/to/dir:$PYTHONPATH

我的目录现在在pythonpath上-

my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...  

我可以从那个目录导入模块。

sys.path的修改只适用于该Python解释器的生命周期。如果要永久执行此操作,则需要修改PYTHONPATH环境变量:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

注意,PATH是可执行文件的系统路径,它是完全独立的。

**您可以在~/.bash_profile中编写上述内容,并使用source ~/.bash_profile将其源代码编写出来

相关问题 更多 >