Skip to content

Instantly share code, notes, and snippets.

View seanh's full-sized avatar

Sean Hammond seanh

View GitHub Profile
@seanh
seanh / detect-filename-clashes.py
Created November 8, 2009 19:50
A Python script to check for matching filenames (regardless of path) in the current working directory. I use this as part of a pre-commit hook with git.
#!/usr/bin/env python
"""
Recursively checks that no filenames from the current working directory
down are the same, even if they are in different subdirectories. Exits
with status 0 if no matching filenames are found, or 1 if a match is
found.
"""
import sys,os
print "Checking for filename clashes...",
@seanh
seanh / gist:232817
Created November 12, 2009 11:07
Adding and removing collide masks (Python, Panda3D)
def addCollideMask(np,mask):
"""Add mask to the NodePath's existing collide mask (do a binary OR of
the two bitmasks)."""
np.setCollideMask(np.getCollideMask() | mask)
def removeCollideMask(np,mask):
"""Remove mask from the NodePath's existing collide mask (all bits set
to 1 in mask will be set to 0 in the NodePath's mask)."""
# Need to copy mask first to avoid modifying it in place.
copy = mask & BitMask32.allOn()
@seanh
seanh / gist:232820
Created November 12, 2009 11:09
Panda3D's BitMask32 class (Python, Panda3D)
# BitMask32 is a class for creating and combining binary bitmasks.
In [5]: BitMask32.allOff()
Out[5]: 0000 0000 0000 0000 0000 0000 0000 0000
In [6]: BitMask32.bit(1)
Out[6]: 0000 0000 0000 0000 0000 0000 0000 0010
In [7]: BitMask32.bit(0)
Out[7]: 0000 0000 0000 0000 0000 0000 0000 0001
@seanh
seanh / gist:232821
Created November 12, 2009 11:11
Creating and removing files and directories with Python os module
"""This is done with the os module, which has lots of methods for handling files and dirs.
<http://docs.python.org/lib/os-file-dir.html>
Effbot's page on the os module: <http://effbot.org/librarybook/os.htm>
The shutil module is useful here also: <http://docs.python.org/lib/module-shutil.html>
"""
import os
@seanh
seanh / gist:232822
Created November 12, 2009 11:12
Create a dict-like object with DictMixin (Python)
"""How to create a custom mappable container (dictionary-like) type in Python."""
from UserDict import DictMixin
class MyDict(DictMixin):
# MyDict only needs to implement getitem, setitem, delitem and keys (at a
# minimum) and UserDict will provide the rest of the standard dictionary
# methods based on these four.
#
# getitem and delitem should raise KeyError if no item exists for the given
@seanh
seanh / gist:232823
Created November 12, 2009 11:14
Formatting dates and times as strings (Python)
"""
[date], [datetime] and [time] objects in Python have a [strftime] method for creating string representations in whatever format you want. (See the strftime link for the strftime syntax.)
[date]: http://docs.python.org/library/datetime.html#datetime.date
[datetime]: http://docs.python.org/library/datetime.html#datetime.datetime
[time]: http://docs.python.org/library/datetime.html#datetime.time
[strftime]: http://docs.python.org/library/datetime.html#strftime-behavior
"""
def format_date_numerical(date):
@seanh
seanh / gist:232824
Created November 12, 2009 11:15
Import a module from a directory (Python)
"""When you want to import a python file but that file is not in the same directory as the python file you're importing from (e.g. it's in a subdir). You need to add the directory that contains the file you want to import to your path environment variable sys.path. sys.path contains all the places python will look for a file when you do an import."""
import sys
sys.path.append('./markdown-1.7')
from markdown import Markdown
@seanh
seanh / gist:232827
Created November 12, 2009 11:16
Creating new sequence types in Python
# See <http://docs.python.org/ref/sequence-types.html>
#
# For a sequence, the allowable keys should be the integers k for which
# 0 <= k < N where N is the length of the sequence, or slice objects,
# which define a range of items.
class MySequence:
def __len__(self):
"""Called to implement the built-in function len(). Should
@seanh
seanh / gist:232828
Created November 12, 2009 11:17
List all the files in a directory with a one-line list comprehension (Python)
# http://www.diveintopython.org/file_handling/os_module.html
# Use a one-line list comprehension to get all the files in a given directory with a given extension.
import os
dir = '.'
ext = '.txt'
txt_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) and f.endswith(ext)]
# os.path.join joins a directory and a filename into a path. You can also split a path name into directory and file with
# os.path.split(), and you can split a filename with extension into filename and extension with os.path.splitext()
@seanh
seanh / gist:232829
Created November 12, 2009 11:19
Writing text files in Python
# Write mode creates a new file or overwrites the existing content of the file.
# Write mode will _always_ destroy the existing contents of a file.
try:
# This will create a new file or **overwrite an existing file**.
f = open("file.txt", "w")
try:
f.write('blah') # Write a string to a file
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()