【问题标题】:Path for python is different than my .bash_profilepython 的路径与我的 .bash_profile 不同
【发布时间】:2017-04-13 21:54:33
【问题描述】:

我正在学习 Python the Hard way,我目前正在练习第 46 题,您将学习如何创建包。我创建了一个基本包,可以进行一些计算,并使用几个不同的模块。

我已经获得了要安装在我的 python2.7 站点包中的包,但事后我似乎无法从我的站点包中运行该模块。我想知道python搜索的路径是否不同,原因如下:

安装后,我看到这条消息Copying story-0.1-py2.7.egg to /usr/local/lib/python2.7/site-packages

但是,当我尝试运行该模块时,我看到了这条消息/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'story.py': [Errno 2] No such file or directory

对不起,如果这完全没有意义,我对编程的奇幻世界很陌生。

【问题讨论】:

  • 你是如何尝试导入/运行story.py的?例如,当您尝试 import story 时会发生什么
  • 我收到 -bash: import: command not found 如果有帮助的话,我正在使用 setup.py 文档安装软件包。
  • 啊,对不起!使用python 开始一个python 会话,然后尝试import story
  • 哇哈哈,我现在应该明白了!所以我运行 python 并执行import story,然后我得到一个带有新命令提示符的新行
  • @ChristopherApple,我只是在命令行中直接输入python story.py 我也只是尝试运行python,然后只输入story。我收到一条消息,上面写着<module 'story' from 'story/__init__.pyc'>

标签: python python-2.7 path


【解决方案1】:

当您安装一个软件包时,您会以不同的方式访问内部结构。你不能再只打电话给python story.py

要访问story.py 中的函数,您需要import 另一个python 文件顶部或解释器中的模块。

如果 story.py 包含

def my_test_function(blah):
    print blah

您可以通过以下方式在另一个文件中使用此功能(在安装模块之后,就像您已经完成的那样)

import story

story.my_test_function("Hello!")

通过导入模块,您可以通过键入module_name.function_name 访问其中的所有函数和类。你也可以直接导入你想使用的函数,看起来像

from story import my_test_function

my_test_function("Hello!")

【讨论】:

  • 好的,有道理。假设story 只是一系列打印命令和对基本数学运算符(加号、减号等)的函数调用。所以现在,我已经修改了 story.py 有一个名为 run_story 的函数,它运行所有的打印命令。我重新安装并将故事导入python,并尝试了story.run_story,但得到了相同的AttributeError: 'module' object has no attribute 'run_story'消息:(
  • 所以我导航到存储它的目录,然后在终端中输入python setup.py install
  • 尝试python setup.py develop,然后再试一次。对此的简要解释是,develop 在进行更改时会自动重新加载模块,非常适合开发
  • 所以试了一下,还是不行。 develop 命令运行得很好,但我仍然无法在 python 中运行我的模块。我冒昧地打印了我的 sys.path,结果就是这样。 ['', '/Users/fuo213/Dropbox/Hotel Stuff/Python/projects/first', '/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
猜你喜欢
  • 2015-12-26
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 2013-10-14
  • 2020-02-18
  • 1970-01-01
  • 2012-01-31
相关资源
最近更新 更多