将带有空格和换行符的字符串作为命令行参数传递 python

Passing a string with spaces and newlines as command line argument python

我试图在名为 main.py 的 python 脚本中传递一个带有空格和换行符的字符串作为命令行参数,但不确定是否可行。

我正在尝试传递字符串 '5 2\n 3 3 2\n 1 1 2' 并让它完全像那样出现在脚本中。为此,我使用 sysargv 这样的:

命令行:

python main.py "5 2\n 3 3 2\n 1 1 2"

Python 脚本:

info_input = sys.argv[1]

然而,它的输出似乎是一个在换行符中添加了转义字符的列表:

['5 2\n 3 3 2\n 1 1 2']

是否可以将其作为参数传递并使 python 中的输出显示为:

"5 2\n 3 3 2\n 1 1 2"

非常感谢

编辑

print(info_input)

'5 2\n 3 3 2\n 1 1 2'

input_split = info_input.split(sep='\n')
print(input_split)

['5 2\n 3 3 2\n 1 1 2']

这里没有换行符,是一个完整的列表。

一个可能的绕过可能是string.replace()。你可以做 '5 2NL 3 3 2NL 1 1 2' 然后 info_input = sys.argv[1].replace("NL", "\n")。在您找到更好的解决方案之前,这可能是一个临时解决方案。

关于你问题的这两点的一些说明

I am trying to pass a string with spaces and newlines

Is it possible to pass this as an arguement and have the output within the python appear as:

当您使用 python main.py "5 2\n 3 3 2\n 1 1 2" 调用脚本时,您并没有传递实际的换行符。 这就是为什么你在你的字符串中得到 \n,Python 正在转义那些 \n,否则这将意味着你的字符串 确实有 换行符。
您混淆了字符串的表示和字符串本身。检查 this question 关于 reprstr.
单独打印字符串时打印效果很好,但打印列表时会显示转义字符,这就解释了为什么会得到不同的结果。

当你这样做时:

input_split = info_input.split(sep='\n')
print(input_split)  

你实际上并没有拆分你的字符串,因为你的字符串不包含换行符 (\n),它包含转义的换行符 (\n)。
如果你真的想在换行符中拆分你的字符串,你可以这样做:

input_split = info_input.split(sep='\n')
print(input_split)  

输出 ['5 2', ' 3 3 2', ' 1 1 2'].


也就是说,如果您的目标是在程序中使用 实际 换行符,您可以用换行符替换转义的换行符:

import sys

info_input = sys.argv[1]
info_input_with_escaped_newlines = info_input
print("info_input_with_escaped_newlines as string", info_input_with_escaped_newlines)
print("info_input_with_escaped_newlines as list", [info_input_with_escaped_newlines])

info_input_with_newlines = info_input.replace('\n', '\n')
print("info_input_with_newlines as string", info_input_with_newlines)
print("info_input_with_newlines as list", [info_input_with_newlines])

输出

> python as.py "5 2\n 3 3 2\n 1 1 2"
info_input_with_escaped_newlines as string 5 2\n 3 3 2\n 1 1 2
info_input_with_escaped_newlines as list ['5 2\n 3 3 2\n 1 1 2']
info_input_with_newlines as string 5 2
 3 3 2
 1 1 2
info_input_with_newlines as list ['5 2\n 3 3 2\n 1 1 2']

注意现在 split 如何拆分 字符串:

import sys

info_input = sys.argv[1].replace('\n', '\n').split(sep='\n')
print(info_input)

输出:

python as.py "5 2\n 3 3 2\n 1 1 2"
['5 2', ' 3 3 2', ' 1 1 2']