【问题标题】:Parsing \ in command line argument - python 2.7.3在命令行参数中解析 \ - python 2.7.3
【发布时间】:2013-02-01 11:52:20
【问题描述】:

我正在调用 python 脚本,parse_input.py 来自 bash

parse_input.py 接受一个命令行参数,其中包含许多 '\n' 字符。

示例输入:

$ python parse_input.py "1\n2\n"

import sys
import pdb

if __name__ == "__main__":

    assert(len(sys.argv) == 2)

    data =  sys.argv[1]
    pdb.set_trace()
    print data

我可以在 pdb 上看到 `data = "1\\n2\\n" 而我想要 data="1\n2\n"

我看到了类似的行为,只是 \(没有 \n)被 \\ 取代

如何删除多余的 \

我不希望脚本将额外的 \ 处理为 也可以从文件中接收相同的输入。

bash 版本:GNU bash,版本 4.2.24(1)-release (i686-pc-linux-gnu)

python 版本:2.7.3

【问题讨论】:

    标签: python bash parsing command-line-arguments


    【解决方案1】:

    Bash 不会解释常规单引号和双引号字符串中的转义字符。要让它解释(某些)转义字符,您可以使用$'...'

       Words of the form $'string' are treated specially.  The word expands to
       string, with backslash-escaped characters replaced as specified by  the
       ANSI  C  standard.  Backslash escape sequences, if present, are decoded
       as follows:
              \a     alert (bell)
              \b     backspace
              \e     an escape character
              \f     form feed
              \n     new line
              \r     carriage return
              \t     horizontal tab
              \v     vertical tab
              \\     backslash
              \'     single quote
              \nnn   the eight-bit character whose value is  the  octal  value
                     nnn (one to three digits)
              \xHH   the  eight-bit  character  whose value is the hexadecimal
                     value HH (one or two hex digits)
              \cx    a control-x character
    
       The expanded result is single-quoted, as if the  dollar  sign  had  not
       been present.
    

    $ python parse_input.py $'1\n2\n'
    

    【讨论】:

    • (+1) 很好,不知道$'...'
    【解决方案2】:

    Bash 不会像 python 那样解释 \n,它会将其视为两个字符。

    可以通过“解码”string_escape 将文字 \n(所以两个字符)解释为 python 中的换行符:

    data = data.decode('string_escape')
    

    演示:

    >>> literal_backslash_n = '\\n'
    >>> len(literal_backslash_n)
    2
    >>> literal_backslash_n.decode('string_escape')
    '\n'
    >>> len(literal_backslash_n.decode('string_escape'))
    1
    

    请注意,其他python string escape sequences 也将被解释。

    【讨论】:

    • Decode 是哪种数据类型的属性?它不适用于我的解释器中的字符串
    • @AshRj:在 python 2 中,str(一个字节字符串)。
    • @AshRj:Python 3,str 是 unicode 类型,所以它有一个 .encode() 方法。 bytes 类型确实有一个 .decode() 方法。
    • 好的。 +1。抱歉,刚刚看到问题确实提到了 Python 2。我之前错过了。
    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2017-10-29
    • 2020-01-01
    • 2011-11-15
    • 2013-03-21
    相关资源
    最近更新 更多