5

我正在parse_input.py从 bash调用 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,版本 4.2.24(1)-release (i686-pc-linux-gnu)

蟒蛇版本:2.7.3

4

2 回答 2

8

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

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

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

于 2013-02-16T16:59:40.603 回答
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.

IE

$ python parse_input.py $'1\n2\n'
于 2013-02-16T17:02:04.753 回答