在命令行参数中解析 \ - Python 2.7.3

5

我正在使用bash调用一个名为parse_input.py的python脚本。

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, version 4.2.24(1)-release (i686-pc-linux-gnu)

python版本:2.7.3

2个回答

8

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字符串转义序列也将被解释。

Decode 是哪种数据类型的属性?在我的解释器中它不能用于字符串。 - asheeshr
@AshRj:在Python 2中,str表示字节串。 - Martijn Pieters
@AshRj:在Python 3中,str是一个Unicode类型,因此它具有.encode()方法。而bytes类型则具有.decode()方法。 - Martijn Pieters
好的。+1。抱歉,刚看到问题中提到了Python 2。之前我没注意到。 - asheeshr

8

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'

3
不错,我不知道 $'...' 这个用法。 - NPE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接