Python Tricks

Network Programming

Socket Programming HOWTO:

https://docs.python.org/2/howto/sockets.html

socket — Low-level networking interface:

https://docs.python.org/2/library/socket.html

Creating a Socket

Create an INET, STREAM[ing] socket. And connect to the web server on port 80 - the typical http port.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 80))

Creating a server socket:

import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Use socket.gethostname() instead of localhost to connect externally.
serversocket.bind(('localhost', 80))
serversocket.listen(5) # Accept 5 simultaneous incoming connections.

Select

select – Wait for I/O Efficiently:

https://pymotw.com/2/select/

Removing files with glob and os.remove

A somewhat perplexing limitation of Pythons ‘os.remove’ finction is that it does not handle wildcards (you might expect it would). So if for instance, your python program creates a number of .bmp image files that you want to clean up, you can’t simply write os.remove('*.bmp'). Luckily there is glob, which does handle wildcards, and allows you to build a list of matching file paths to feed to os.remove. For example:

import os
import glob

file_list = glob.glob('<some_file_path>/*.bmp')
    for file_path in file_list:
        os.remove(file_path)