gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:25:21 26 4
gpt4 key购买 nike

我正在从 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

最佳答案

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'

关于python - 解析\在命令行参数 - python 2.7.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14912771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com