Skip to content

Instantly share code, notes, and snippets.

@Boldewyn
Created April 15, 2014 10:39
Show Gist options
  • Save Boldewyn/10721736 to your computer and use it in GitHub Desktop.
Save Boldewyn/10721736 to your computer and use it in GitHub Desktop.
a small URL encoding script
#!/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