no module named urllib.parse (How should I install it?)

I'm trying to run a REST API on CentOS 7, I read urllib.parse is in Python 3 but I'm using Python 2.7.5 so I don't know how to install this module.

I installed all the requirements but still can't run the project.

When I'm looking for a URL I get this (I'm using the browsable interface):

Output:

ImportError at /stamp/
No module named urllib.parse

Solution 1:

If you need to write code which is Python2 and Python3 compatible you can use the following import

try:
    from urllib.parse import urlparse
except ImportError:
     from urlparse import urlparse

Solution 2:

You want urlparse using python2:

from urlparse import urlparse

Solution 3:

With the information you have provided, your best bet will be to use Python 3.x.

Your error suggests that the code may have been written for Python 3 given that it is trying to import urllib.parse. If you've written the software and have control over its source code, you should change the import to:

from urlparse import urlparse

urllib was split into urllib.parse, urllib.request, and urllib.error in Python 3.

I suggest that you take a quick look at software collections in CentOS if you are not able to change the imports for some reason. You can bring in Python 3.3 like this:

  1. yum install centos­-release­-SCL
  2. yum install python33
  3. scl enable python33

Check this page out for more info on SCLs

Solution 4:

python3 supports urllib.parse and python2 supports urlparse

If you want both compatible then the following code can help.

import sys

if ((3, 0) <= sys.version_info <= (3, 9)):
    from urllib.parse import urlparse
elif ((2, 0) <= sys.version_info <= (2, 9)):
    from urlparse import urlparse

Update: Change if condition to support higher versions if (3, 0) <= sys.version_info:.

Solution 5:

Install six, the Python 2 and 3 Compatibility Library:

$ sudo -H pip install six

Use it:

from six.moves.urllib.parse import urlparse

(edit: I deleted the other answer)