Python 脚本:在 Shell 中运行,但在现实生活中失败,因为无法导入模块
我有一个在 Python Shell 中运行良好的脚本,但是双击时无法导入 PIL 模块(但它确实在 Shell 中导入了 PIL 模块)。
怎么了?我需要不同的 shebang 吗?我在 Windows 7 上:
#!/usr/bin/env python
"""
"""
try:
from PIL import Image
import os
import datetime
import time
except Exception, e:
raw_input(str(e))
# Running this script in the Shell, the code gets to here
# Running this script in real life (just double click it) it prints "no module PIL"
I have a script that runs fine in the Python Shell, but when double clicked it fails to import the PIL module(but it does import the PIL module in the Shell).
What is wrong? Do I need a different shebang? I am on Windows 7:
#!/usr/bin/env python
"""
"""
try:
from PIL import Image
import os
import datetime
import time
except Exception, e:
raw_input(str(e))
# Running this script in the Shell, the code gets to here
# Running this script in real life (just double click it) it prints "no module PIL"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将这些行添加
到您的代码中。当您在 shell 中运行它时,您会发现它是一个不同的 python 可执行文件,而不是双击 .py 文件。
如果您想控制使用哪个已安装的 python 版本来运行脚本,而不是简单地运行脚本,请在 Windows 命令窗口中键入如下内容。
根据需要替换 python 目录和脚本名称。
Add the lines
to your code. You'll see that it's a different python executable when you run it in the shell, vs. double clicking the .py file.
If you want to control which installed version of python is used to run your script, rather than simply running the script, type something like the following in a windows command window.
replacing the python directory and script name as appropriate.
Windows 会忽略 shebang 行(即使它会尊重它,它也无法执行
/usr/bin/env
—— Windows 上不存在它)。在资源管理器中双击可启动与.py
扩展名关联的程序的脚本。检查您是否已将其设置为正确的 Python 版本。Windows ignores the shebang line (even if it would respect it, it wouldn't be able to execute
/usr/bin/env
-- it doesn't exist on Windows). Double-clicking in the explorer starts the script with the program associated with the.py
extension. Check that you have set this to the right version of Python.听起来您为不同版本的 Python 安装了 PIL,而不是设置为在 Windows 中打开 .py 文件。如果您使用的是 Python 2.7,PIL 会将自身安装到
C:\Python27\Lib\site-packages\PIL
中,在这种情况下,您需要确保 Windows 使用C 打开 .py 文件:\Python27\python.exe
。您可以右键单击.py文件,单击打开方式->选择默认程序...将其设置为您为其安装 PIL 的 Python 版本。Sounds like you have PIL installed for a different version of Python than is set to open .py files in Windows. PIL installs itself into
C:\Python27\Lib\site-packages\PIL
if you are using Python 2.7, in which case you'd want to make sure Windows opens .py files withC:\Python27\python.exe
. You can right click on the .py file, click Open With -> Choose default program... to set it to the version of Python you've installed PIL for.我也遇到了这个问题,但意识到我需要更新
app.yaml
文件。将其粘贴到libraries
下:I was having this problem too but realized I needed to update the
app.yaml
file. Paste this underlibraries
: