Sockets are the lead pipes of computer networks: they let you connect with other devices so that information can flow freely. As you might expect, they're widely used on the Internet. Peyton McCullough explains how to code sockets in Python.
While the socket library is good for many things, there are several libraries built on the socket library that make development easier and faster. Say you wanted to connect to the official Python site to retrieve a piece of information. You could accomplish this task with the socket library, but there's no use working at such a low level when other libraries could do this in a shorter amount of lines. There are libraries for HTTP, FTP, Gopher, telnet and more.
A Real-World Problem and a Pythonic Solution
Let's say that you need to convert United States Dollars into Euros. This may seem complex at first, but it really isn't. It can be accomplished with sockets. We'll use the urllib library to connect to 'http://xe.com' and convert ten dollars into Euros.
Open up the Python command line and import the urllib module:
>>> import urllib
Connecting to the currency converter website I mentioned is simple with the urllib library -- a lot simpler than it would have been if I had used the socket library alone. It can be accomplished with the following line of code:
We can use regular expressions to sort through all the junk and take out the figures we need from the above code:
>>> import re >>> euros = re.search ( '(\d*)\.(\d*) EUR', data ) >>> print '10 United States Dollars are equal to...' >>> print euros.group ( 1 ) + '.' + euros.group ( 2 ), 'Euros.'
We also need to clean up and close the connection like we did earlier:
>>> currency.close()
That's it, we've solved our problem in only a few lines! If we were to do it with the socket library, however, it would have required a number of more lines to accomplish the same result.