Search code examples
pythondjangourllib2pythonanywhere

Python Anywhere issue using Urllib2 with virtualenv


I'm using a Django server on PythonAnywhere, using a virtualenv. In the server I'm using a scraping code to write a text file, the code uses urllib2 which should come bundled in python by default but there are various errors :

pip install urllib2

Could not find a version that satisfies the requirement urllib2 (from versions: )
No matching distribution found for urllib2

apt-get install python-urllib2

E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied) E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

Of course the root of the issue is this (from python console) :

import urllib2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'urllib2'

Solution

  • In Python 2, urllib2 is part of the standard library. You don't have to install it with pip or your package manager, it is already part of your Python 2 installation.

    The pip command fails because there is no external package urllib2 to install.

    The apt-get command fails because you do not have the correct permissions. Even if you used sudo or switched to root, it would fail because Python-urllib2 does not exist.

    If you are using Python 3, the urllib2 module no longer it exists, and has been split between urllib.request and urllib.error. You need to update your code to use the new urllib module in Python 3.