#!/usr/bin/env python # Encode/decode url strings in stdin or the given file(s). import getopt import fileinput import sys import os try: from urllib.parse import quote_plus, quote, unquote_plus, unquote except ImportError: from urllib import quote_plus, quote, unquote_plus, unquote # def encode(text, plus=False): return quote(text.strip()) def encode_plus(text): return quote_plus(text.strip()) def decode(text): return unquote(text.strip()) def decode_plus(text): return unquote_plus(text.strip()) def usage(): # TODO Improve this print("Usage: {} [-edEDh] file1[ file2[ ...]]".format(os.path.basename(sys.argv[0]))) # if __name__ == '__main__': COMMANDS = { "-e": encode, "-E": encode_plus, "-d": decode, "-D": decode_plus } try: optlist, args = getopt.getopt(sys.argv[1:], 'edEDh') sys.argv = [sys.argv[0]] + args except getopt.GetoptError as err: print(err) sys.exit(1) action = encode for o, a in optlist: if o in COMMANDS: action = COMMANDS[o] elif o == '-h': usage() sys.exit() else: assert False, "unhandled option" input = "\n".join([line for line in fileinput.input()]) print(action(input))