解析命令行参数中的\ - python 2.7.3

5 投票
2 回答
2895 浏览
提问于 2025-04-17 16:06

我在用bash调用一个python脚本,叫做parse_input.py

这个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

2 个回答

8

Bash(一个命令行工具)对待 \n 的方式和 Python 不一样,它把 \n 看成两个字符,而不是一个换行符。

在 Python 中,你可以通过 '解码' 来把字面上的 \n(也就是两个字符)当成换行符来使用,这个过程叫做从 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 字符串转义序列 也会被 解释

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'

撰写回答