Skip to content

Instantly share code, notes, and snippets.

@seanh
Created April 11, 2009 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanh/93702 to your computer and use it in GitHub Desktop.
Save seanh/93702 to your computer and use it in GitHub Desktop.
A little script that I use when I want to add an entry to my pyblosxom blog. Given a title it creates the file for me and deals with adding timestamps and figuring out a filename.
#!/usr/bin/env python
# TODO: support specifying categories on the command-line with tab-complete.
# TODO: support specifying extension as a command-line argument
# TODO: support specifying notes_dir as an option
# TODO: published_key, modified_key and timestr as command-line options
# TODO: specify editor on the command-line, or fall back on $EDITOR.
# TODO: support specifying a template to be used to create the file.
import os,sys,datetime,string
notes_dir = os.path.expanduser('~/Desktop/')
ext = 'txt'
published_key = "published"
modified_key = "modified"
timestr = "%Y-%m-%d %H:%M:%S"
now = datetime.datetime.now().strftime(timestr)
editor = 'scribes'
def format_filename(s):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores.
Note: this method may produce invalid filenames such as ``, `.` or `..`
When I use this method I prepend a date string like '2009_01_15_19_46_32_'
and append a file extension like '.txt', so I avoid the potential of using
an invalid filename.
"""
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
s = s.replace('&','and')
filename = ''.join(c for c in s if c in valid_chars)
filename = filename.replace(' ','_') # I don't like spaces in filenames.
filename = filename.lower() # I prefer all lowercase filenames
return filename
def usage():
return 'Syntax: blog "title for my new blog post"'
if __name__ == "__main__":
if len(sys.argv) != 2:
print usage()
sys.exit(2)
title = sys.argv[1]
filename = format_filename(title)
path = os.path.join(notes_dir,filename) + '.' + ext
if os.path.exists(path):
print 'Path already exists!'
print path
sys.exit(2)
try:
f = open(path,'w')
try:
f.write(title+'\n')
f.write('#'+published_key+' '+now+'\n')
f.write('#'+modified_key+' '+now+'\n')
f.write('\n')
finally:
f.close()
except IOError, e:
print 'IOError when writing file '+path
print e
sys.exit(2)
os.system(editor+' "'+path+'"')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment