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

Pra*_*mod 5 python bash parsing command-line-arguments

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
Run Code Online (Sandbox Code Playgroud)

我可以在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

Mar*_*ers 8

Bash不解释\npython的方式,它将其视为两个字符.

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

data = data.decode('string_escape')
Run Code Online (Sandbox Code Playgroud)

示范:

>>> literal_backslash_n = '\\n'
>>> len(literal_backslash_n)
2
>>> literal_backslash_n.decode('string_escape')
'\n'
>>> len(literal_backslash_n.decode('string_escape'))
1
Run Code Online (Sandbox Code Playgroud)

请注意,其他Python字符串转义序列被解释.


Kev*_*vin 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.
Run Code Online (Sandbox Code Playgroud)

$ python parse_input.py $'1\n2\n'
Run Code Online (Sandbox Code Playgroud)

  • (+1)很好,不知道'$'......'`. (3认同)