Passing meta-characters to Python as arguments from command line

前端 未结 4 773
一生所求
一生所求 2020-12-11 03:37

I\'m making a Python program that will parse the fields in some input lines. I\'d like to let the user enter the field separator as an option from the command line. I\'m usi

相关标签:
4条回答
  • 2020-12-11 03:37

    solving it from within your script:

    options.delimiter = re.sub("\\\\t","\t",options.delimiter)
    

    you can adapt the re about to match more escaped chars (\n, \r, etc)

    another way to solve the problem outside python:

    when you call your script from shell, do it like this:

    parseme.py -f input.txt -d '^V<tab>'
    

    ^V means "press Ctrl+V"

    then press the normal tab key

    this will properly pass the tab character to your python script;

    0 讨论(0)
  • 2020-12-11 03:38
    >>> r'\t\n\v\r'.decode('string-escape')
    '\t\n\x0b\r'
    
    0 讨论(0)
  • 2020-12-11 03:39

    The callback option is a good way to handle tricky cases:

    parser.add_option("-d", "--delimiter", action="callback", type="string",
                      callback=my_callback, default='\t')
    

    with the corresponding function (to be defined before the parser, then):

    def my_callback(option, opt, value, parser):
        val = value
        if value == '\\t':
            val = '\t'
        elif value == '\\n':
            val = '\n'
        parser.values.delimiter = val
    

    You can check this works via the command line: python test.py -f test.txt -d \t (no quote around the \t, they're useless).

    It has the advantage of handling the option via the 'optparse' module, not via post-processing the parsing results.

    0 讨论(0)
  • 2020-12-11 04:02

    The quick and dirty way is to to eval it, like this:

    eval(options.delimiter, {}. {})
    

    The extra empty dicts are there to prevent accidental clobbering of your program.

    0 讨论(0)
提交回复
热议问题