ImportError: No module named request

ubuntu中运行python脚本出现:ImportError: No module named request错误

 之前在ubuntu中运行python脚本实现下载图片,程序中用到了urllib.request模块:

import urllib.request

 使用命令下载了python-requests包:

sudo apt-get install python-requests

 但是运行程序仍然报:ImportError: No module named request错误,如下图:

原因:python2中urllib moudle中并没有request相关方法,而是直接用urlopen方法,在python3中才有request相关方法。 

解决方法:

 如果你使用的是python3 xx.py命令运行python脚本,则需要使用代码:

import urllib.request
req=urllib.request.urlopen(img_url)  #即urllib后面跟上.request

 如果你使用的是python2 xx.py命令运行python脚本,则需要使用代码:

import urllib
req=urllib.urlopen(img_url)  #即导入模块urllib,并直接使用urlopen()方法

注:ubuntu中python默认使用的版本是:Python 2.7.12,如果想要查看自己ubuntu中python版本,并且修改ubuntu中python默认使用的版本为:Python 3.5.2,详细介绍请看:https://blog.csdn.net/qq_40808154/article/details/89252883

猜你喜欢

转载自blog.csdn.net/qq_40808154/article/details/89255435