Module cannot be found when using “pythonw” (instead of “python”) to run an application

爱⌒轻易说出口 提交于 2019-12-24 05:11:36

问题


I tried this minimal example:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug = True)

When I try python hello.py, everything goes well. However, when I try to run it from Textmate (Shift + Cmd + R) an error is thrown:

Traceback (most recent call last):
  File "/Users/user/EventFeed/hello.py", line 1, in <module>
    from flask import Flask
ImportError: No module named flask

Textmate calls pythonw instead of python. When I try pythonw myself the same error is thrown.

The man pythonw states that As of Python 2.5, python and pythonw are interchangeable though they appear not to be in this case.

Would you have an idea of what happens?

(Question Code that works with python and not with pythonw does not answer the question despite its similar title.)


回答1:


The problem is that your pythonw and your python are not pointing at the same Python installations.

Why?

Most likely because you've installed a second Python 2.7 that doesn't include the obsolete pythonw, but Apple's pre-installed Python 2.7 definitely does include it.

The quickest way to check this is the which command. For example, on one of my machines:

$ which python
/usr/local/bin/python
$ which pythonw
/usr/bin/pythonw

That first one is a symlink to a Homebrew install of Python 2.7, while the second is Apple's Python 2.7. Your exact details may differ; the first one may be a symlink to /Library/Frameworks/Python.framework/Versions/2.7/bin/python, or a wrapper executable that actually lives in /usr/local/bin, or it may be in /opt/local, etc. The point is that they're not in the same directories.

At any rate, your two separate installations of Python don't share the same site-packages (and they shouldn't), so the fact that you've installed Flask for the second one doesn't help the Apple one. You can verify this by running them and printing out sys.path:

$ python
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.7/site-packages', …]
>>> ^D
$ pythonw
>>> import sys
>>> sys.path
['', '/Library/Python/2.7/site-packages', …]
>>> ^D

Anyway, the simplest solution is to configure your editor to run python instead of pythonw—or, better, give it an absolute path to a Python interpreter like /usr/local/bin/python2.7 to make absolutely sure you know what you're running.

(I don't know TextMate very well, but from this source it looks like it has a setting named TM_PYTHON that should control this…)



来源:https://stackoverflow.com/questions/26049778/module-cannot-be-found-when-using-pythonw-instead-of-python-to-run-an-appl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!