Handling argparse escaped character as option

Assuming that the question was partially about how to carry out the post-processing explained by @hpaulj and since I couldn't see an immediate solution for Python 3 in the links above, here is a quick solution:

import codecs

def unescaped_str(arg_str):
    return codecs.decode(str(arg_str), 'unicode_escape')

then in the parser:

parser.add_argument('-d', '--delimiter', type=unescaped_str, default='\t')

This will make your less desirable cases work:

parser.py -d '\t'
parser.py -d "\t"

But not the desired unescaped \t. In any case, this solution can be dangerous as there is no check mechanism...


The string that you see in the namespace is exactly the string that appears in sys.argv - which was created by bash and the interpreter. The parser does not process or tweak this string. It just sets the value in the namespace. You can verify this by print sys.argv before parsing.

If it is clear to you what the user wants, then I'd suggest modifying args.delimiter after parsing. The primary purpose of the parser is to figure out what the user wants. You, as programmer, can interpert and apply that information in any way.

Once you've worked out a satisfactory post-parsing function, you could implement it as a type for this argument (like what int() and float() do for numerical strings). But focus on the post-parsing processing.