Skip to content

Instantly share code, notes, and snippets.

@xZise
Last active August 29, 2015 14:05
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 xZise/643e85f92f69fc0a69df to your computer and use it in GitHub Desktop.
Save xZise/643e85f92f69fc0a69df to your computer and use it in GitHub Desktop.
Rewrite the parameters to be readable by argpare
['-o', 'hello world']
['-o', 'hello world']
False
None
hello world
['-o', 'hello world', '-p:page']
['-o', 'hello world', '-p=page']
False
page
hello world
['-o', 'hello world', '-p:page', '--keep']
['-o', 'hello world', '-p=page', '--keep']
True
page
hello world
['--keep', '-o', 'hello world']
['--keep', '-o', 'hello world']
True
None
hello world
['--keep', '-o:hello', '-p', 'world']
['--keep', '-o=hello', '-p', 'world']
True
world
hello
['--keep', '-o:hello world', '-p', 'world']
['--keep', '-o=hello world', '-p', 'world']
True
world
hello world
['--keep', '-o:hello', '-p', 'scyscraper world']
['--keep', '-o=hello', '-p', 'scyscraper world']
True
scyscraper world
hello
['--keep', '-o', 'Wikipedia:Help', '-p', 'scyscraper world']
['--keep', '-o', 'Wikipedia:Help', '-p', 'scyscraper world']
True
scyscraper world
Wikipedia:Help
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import shlex
valid_warnings = ['foo', 'bar']
parser = argparse.ArgumentParser()
parser.add_argument('--keep', action='store_true')
parser.add_argument('-p', '--page', '-page')
parser.add_argument('-o', '--other', '-other')
def test(a):
try:
r = parser.parse_args(a)
print(r.keep)
print(r.page)
print(r.other)
except SystemError as e:
print(e.message)
def rewrite(args):
if isinstance(args, basestring):
args = shlex.split(args)
new_args = []
for arg in args:
if arg[0] == '-':
separator = len(arg)
if ' ' in arg:
separator = arg.index(' ')
if '=' in arg:
separator = min(arg.index('='), separator)
if ':' in arg:
pos = arg.index(':')
if separator > pos:
arg = arg[:pos] + '=' + arg[pos+1:]
new_args += [arg]
print args
print new_args
test(new_args)
rewrite(['-o', 'hello world'])
rewrite(['-o', 'hello world', '-p:page'])
rewrite(['-o', 'hello world', '-p:page', '--keep'])
rewrite('--keep -o "hello world"')
rewrite('--keep -o:hello -p world')
rewrite('--keep -o:"hello world" -p world')
rewrite('--keep -o:hello -p "scyscraper world"')
rewrite('--keep -o "Wikipedia:Help" -p "scyscraper world"')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment