Skip to content

Instantly share code, notes, and snippets.

@ruo91
Created May 16, 2023 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruo91/30123a423fba0afe85850761ddd46970 to your computer and use it in GitHub Desktop.
Save ruo91/30123a423fba0afe85850761ddd46970 to your computer and use it in GitHub Desktop.
Python3 - URL Encode
# - Usage
# ex1)
# python3 url_encode.py "Blah~ Blah~"
#
# ex2)
# python3 url_encode.py "/path/to/directory/example.txt"
#
# - RefURL
# https://gist.github.com/Paradoxis/6336c2eaea20a591dd36bb1f5e227da2
#
#!/usr/bin/env python3
from argparse import ArgumentParser
from sys import stdin, stdout, argv
from urllib.parse import quote as url_encode
def aggressive_url_encode(string):
return "".join("%{:02x}".format(ord(char)) for char in string)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("-a", "--agressive", help="Forcibly encode every character rather than non-url safe characters", action="store_true")
parser.add_argument("string", nargs="*")
args = parser.parse_args()
if args.agressive:
if args.string:
print(aggressive_url_encode(" ".join(args.string)), end='\n')
else:
print(aggressive_url_encode(stdin.read()[:-1]), end='\n')
else:
if args.string:
print(url_encode(" ".join(args.string)), end='\n')
else:
print(url_encode(stdin.read()[:-1]), end='\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment