Error:

TCP client example

import socket

HOST = 'localhost'
PORT = 3000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello')
reply = s.recv(1024)
s.close()
print 'Received: ', repr(data)

TCP server example (socket)

import socket
import datetime

HOST = ''
PORT = 3000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
    conn, addr = s.accept()
    print 'Connection from: ', addr
    conn.send(str(datetime.datetime.now()))
    conn.send("\nBye\n")
    conn.close()

TCP server example (SocketServer)

import SocketServer
import datetime

class DatetimeTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print "Connection from %s:%d" % self.client_address
        self.request.sendall(str(datetime.datetime.now()))
        self.request.sendall("\nBye\n")

HOST, PORT = "localhost", 3001
server = SocketServer.TCPServer((HOST, PORT), DatetimeTCPHandler)
server.serve_forever()

UDP client example

import socket

HOST = "localhost"
PORT = 3001
MESSAGE = "Hello!\n"

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (HOST, PORT))

UDP server example (socket)

import socket

HOST = "localhost"
PORT = 3000

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST, PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print "received message: ", data

UDP server example (SocketServer)

import SocketServer
import datetime

class DatetimeUDPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]

        args = self.client_address + (data,)
        print "Request from %s:%d: %s" % args
        socket.sendto(str(datetime.datetime.now()), self.client_address)
        socket.sendto("\nBye\n", self.client_address)

HOST, PORT = "localhost", 3001
server = SocketServer.UDPServer((HOST, PORT), DatetimeUDPHandler)
server.serve_forever()

Fetch file over HTTP (urllib2)

url = "http://bluezbox.com/audiobookbinder/AudiobookBinder-1.18.dmg"
filename = url.split('/')[-1]

u = urllib2.urlopen(url)
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s (%s bytes)" % (filename, file_size)

output = open(filename,'wb')
output.write(u.read())
output.close()

Fetch file over HTTP (requests)

# Install requests from http://www.python-requests.org/
import requests

url = "http://bluezbox.com/audiobookbinder/AudiobookBinder-1.18.dmg"
filename = url.split('/')[-1]
r = requests.get(url)
if r.status_code == 200:
    with open(filename, 'wb') as f:
        for chunk in r.iter_content(4096):
            f.write(chunk)

Submit form using GET method (urllib2)

import urllib
import urllib2

url = "http://duckduckgo.com/"
data = urllib.urlencode({'q': 'CodeGofer'})
url += '?' + data
results = urllib2.urlopen(url)
with open("results-codegofer.html", "w") as f:
    f.write(results.read())

Submit form using GET method (requests)

# Install requests from http://www.python-requests.org/
import requests

url = "http://duckduckgo.com/"
data = {'q': 'CodeGofer'}
r = requests.get(url, params=data)
if r.status_code == 200:
    html = r.text

Submit form using POST method (urllib2)

import urllib
import urllib2

url = "http://quackquack42.com/search"
data = urllib.urlencode({'q': 'CodeGofer'})
# POST request if data is not None
results = urllib2.urlopen(url, data)
with open("results-codegofer.html", "w") as f:
    f.write(results.read())

Submit form using POST method (requests)

# Install requests from http://www.python-requests.org/
import requests

url = "http://quackquack42.com/search"
data = {'q': 'CodeGofer'}
r = requests.post(url, params=data)
if r.status_code == 200:
    html = r.text

Parse URI

from urlparse import urlparse
obj = urlparse('http://example.com/cgi-bin/test.cgi?q=echo')
obj.scheme   # "http"
obj.netloc   # "example.com"
obj.path     # "/cgi-bin/test.cgi"
obj.query    # "q=echo"

Send email (smtp)

import smtplib
from email.mime.text import MIMEText

textfile = 'msg.txt'
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

sender = 'noreply@quackquack42.com'
to = 'info@quackquack42.com'
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = sender
msg['To'] = to

s = smtplib.SMTP('localhost')
s.sendmail(sender, [to], msg.as_string())
s.quit()

Send email (sendmail)

from email.mime.text import MIMEText
from subprocess import Popen, PIPE

msg = MIMEText("Alert! Server is down!!!")
msg["From"] = "noreply@quackquack42.com"
msg["To"] = "info@quackquack42.com"
msg["Subject"] = "Something is wrong"
p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
p.communicate(msg.as_string())