Skip to content

Instantly share code, notes, and snippets.

@bedge
Created May 11, 2018 23:46
Show Gist options
  • Save bedge/4b130238dfaa70d7956128190632fcec to your computer and use it in GitHub Desktop.
Save bedge/4b130238dfaa70d7956128190632fcec to your computer and use it in GitHub Desktop.
Script to allow html/url encode/decode of file(s)/stdin.
#!/usr/bin/env python3
# Suggested use:
# alias urldecode="endecode.py -a url_decode $*"
# alias urlencode="endecode.py -a url_encode $*"
# alias htmldecode="endecode.py -a html_decode $*"
# alias htmlencode="endecode.py -a html_encode $*"
# Encode or decode url or html encoded/plain files.
import sys
import fileinput
import argparse
import html
import urllib.parse as ul
VERSION = '0.1.0'
action_map = {
"html_encode": lambda str: html.escape(str),
"html_decode": lambda str: html.unescape(str),
"url_encode": lambda str: ul.unquote_plus(str),
"url_decide": lambda str: ul.quote_plus(str)
}
# python3 https://www.python.org/dev/peps/pep-0448/
actions = [*action_map.keys()]
# Set up the command line parser. The -h and --help switches are automatically
# enabled. See http://docs.python.org/library/argparse.html
#
ap = argparse.ArgumentParser(description='Utility for processing text.')
ap.add_argument('-v', '--version', action='version', version='%(prog)s ' + VERSION)
ap.add_argument('-l', '--list', action='store_true')
ap.add_argument('files', metavar='FILE', nargs='*',
help='the files to read')
ap.add_argument('-a', '--action', action='store', choices=actions,
default=actions[0], help='List filenames')
args = ap.parse_args()
# Iterate over all input files: If no file names are given on the command line,
# read from stdin. Otherwise iterate over all given files, with '-' being
# stdin. See http://docs.python.org/library/fileinput.html
#
with fileinput.input(args.files) as f:
for line in f:
if args.list and f.isfirstline():
print('==>', f.filename(), '<==', file=sys.stderr)
print(action_map[args.action](line),end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment