Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用argparse使用换行符分析文本_Python_Python 3.x_Argparse - Fatal编程技术网

Python 使用argparse使用换行符分析文本

Python 使用argparse使用换行符分析文本,python,python-3.x,argparse,Python,Python 3.x,Argparse,在Python中,使用,是否有任何方法来解析包含作为参数给定的换行符的文本 我有这个剧本: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('text', help='some text with newline')

在Python中,使用,是否有任何方法来解析包含作为参数给定的换行符的文本

我有这个剧本:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('text', help='some text with newline')

args = parser.parse_args(["line1\nline2"])

print(args.text)
按预期打印:

line1
line2
但是如果我在命令行中给出参数(在上面的脚本中更改为
args=parser.parse_args()
之后),它就不会这样做了。例如:

$。/newline2argparse.py“line1\nline2”
第1行\n第2行

对此有什么想法吗?

您的
\n
被视为
\
,后面跟着
n
,而不是按其应有的方式解释。使用类似于
echo
printf
的命令来正确解释它。这几乎适用于任何shell(
sh
bash
zsh
,等等)

$。/newline2argparse.py“$(echo-en'line1\nline2')”
$./newline2argparse.py“$(printf'line1\nline2')”
$./newline2argparse.py`printf“line1\nline2”`

有很多替代方法。

如果您希望在shell字符串中处理转义序列,请使用
$''


请注意,这是一个
bash
扩展,它可能不受所有其他shell的支持。

您的shell不会将
\n
解释为换行符。您正在使用的是bash吗?
哪个$SHELL
打印
/bin/bash
。我用的是Mac操作系统。但是在python脚本中应该有一种方法来处理这个问题?据介绍,您可以使用
/newline2argparse.py$'line1\nline2'
。接受这个答案是因为它在shell中看起来更“通用”,但是@Barmar answer对于
bash
更简洁。
./newline2argparse.py $'line1\nline2'