Created
April 15, 2014 10:39
-
-
Save Boldewyn/10721736 to your computer and use it in GitHub Desktop.
a small URL encoding script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
"""Simple URL encoder""" | |
import argparse | |
import urllib | |
parser = argparse.ArgumentParser(description='URL-encode a string') | |
parser.add_argument('file', type=argparse.FileType('rb'), nargs='?', | |
default="-", | |
help='file to encode (default: stdin). Use "-" for explicit stdin.') | |
parser.add_argument('--output', '-o', type=argparse.FileType('wb'), | |
default="-", | |
help='target file (default: stdout). Use "-" for explicit stdout.') | |
parser.add_argument('--safe', '-s', default='/=', | |
help='safe characters (will not be encoded. Default: %(default)s)') | |
parser.add_argument('--trim', '-t', action="store_true", default=False, | |
help='whether to trim the input before encoding') | |
args = parser.parse_args() | |
def trim(s): | |
"""trim s, if user requests it""" | |
if args.trim: | |
return s.strip() | |
return s | |
try: | |
args.output.write( | |
urllib.quote( | |
trim( | |
args.file.read() | |
), | |
safe=args.safe | |
) | |
) | |
except KeyboardInterrupt: | |
exit(1) | |
else: | |
if args.output.isatty(): | |
# end stdout with a newline. Any \n from input is escaped | |
args.output.write("\n") | |
finally: | |
args.file.close() | |
args.output.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment