Skip to content

Instantly share code, notes, and snippets.

@dsc
Created February 23, 2010 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dsc/311768 to your computer and use it in GitHub Desktop.
Save dsc/311768 to your computer and use it in GitHub Desktop.
A simple URI Encoding/Decoding commandline tool.
#!/usr/bin/env python
# encoding: utf-8
""" A simple URI Encoding/Decoding commandline tool.
"""
__author__ = 'David Schoonover <dsc@less.ly>'
__date__ = '2009-06-05'
__version__ = (0, 0, 1)
import sys, select, urllib
def main():
from optparse import OptionParser
parser = OptionParser(
usage = 'usage: %prog [options] [STRINGS...]',
version = '%prog'+" %i.%i.%i" % __version__)
parser.add_option("-d", "--decode", default=False, action="store_true",
help="Perform decoding rather than encoding.")
parser.add_option("-p", "--plus", dest="plus", default=True, action="store_true",
help="Encode as a fragment rather than a full URL.")
parser.add_option("-P", "--no-plus", dest="plus", action="store_false",
help="Encode as a full URL rather than a fragment.")
parser.add_option("-f", "--file", help="Run on file contents.")
parser.add_option("-D", "--delimiter", default=" ", help="Join delimiter. [default: '%default']")
(options, strings) = parser.parse_args()
if options.plus:
encode = urllib.quote_plus
decode = urllib.unquote_plus
else:
encode = urllib.quote
decode = urllib.unquote
if strings:
s = options.delimiter.join(strings)
else:
stdin = select.select([sys.stdin], [], [], 0.1)[0]
s = stdin[0].read() if stdin else ''
if options.decode:
out = decode(s)
else:
out = encode(s)
# Add a newline if this is writing to a terminal
sys.stdout.write(out)
if sys.stdout.isatty(): sys.stdout.write('\n')
return 0
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment