在Windows中将多行字符串作为参数传递给脚本

9

我有一个简单的Python脚本,如下所示:

import sys

lines = sys.argv[1]

for line in lines.splitlines():
    print line

我希望能够从命令行(或.bat文件)调用它,但第一个参数可能(并且很可能)是一个包含多行字符串的文本。如何做到这一点?

当然,这是可行的:

import sys

lines = """This is a string
It has multiple lines
there are three total"""

for line in lines.splitlines():
    print line

但我需要能够逐行处理参数。

编辑:这可能更多是Windows命令行问题,而不是Python问题。

编辑2:感谢所有好的建议。看起来似乎不可能。我不能使用另一个shell,因为我实际上是在尝试从另一个程序中调用脚本,该程序似乎在后台使用Windows命令行。


我不明白 - 你现在的代码不起作用吗? - Andrew Hare
你应该先按 "\n" 分割并删除 "\r",以获得更好的平台兼容性。bash 在它的参数中会加入回车符吗?(不确定)。 - Lucas Jones
你根本不应该使用字符串模块。那一行代码应该写成 lines = multiline.splitlines() - Devin Jeanpierre
所有的建议都很好。我目前对Python的总体经验大约只有一个小时。 - Zack The Human
6个回答

4

我知道这个帖子已经很老了,但是当我试图解决一个类似的问题时,我遇到了它,其他人也可能会遇到,所以让我向您展示我如何解决它。

这至少适用于Windows XP Pro,在名为"C:\Scratch\test.py"的文件中使用Zack的代码:

C:\Scratch>test.py "This is a string"^
More?
More? "It has multiple lines"^
More?
More? "There are three total"
This is a string
It has multiple lines
There are three total

C:\Scratch>

这个比上面Romulo的解决方案更易读。


2

只需将参数用引号括起来:

$ python args.py "This is a string
> It has multiple lines
> there are three total"
This is a string
It has multiple lines
there are three total

1

以下可能有效:

C:\> python something.py "This is a string^
More?
More? It has multiple lines^
More?
More? There are three total"

这让我可以有效地跨越多行来拼接我的字符串,但最终字符串中不会包含“换行符”字符。 - Zack The Human
1
在这种情况下,空行很重要。至少对于echo输出多行来说是有效的,但我目前无法在此处进行测试。如果其他方法都失败了,请使用其他人建议的管道解决方案。通过stdin传递多行没有问题,至少如此。 - Joey

1

这是我唯一行得通的方法:

C:\> python a.py This" "is" "a" "string^
More?
More? It" "has" "multiple" "lines^
More?
More? There" "are" "three" "total

对我来说, Johannes' solution 在第一行末尾调用了 Python 解释器,所以我没有机会传递额外的行。

但是你说你是从另一个进程中调用 Python 脚本,而不是从命令行中调用。那么为什么不使用 dbr' solution?这个解决方案对我作为 Ruby 脚本起作用:

puts `python a.py "This is a string\nIt has multiple lines\nThere are three total"`

你用什么语言编写调用 Python 脚本的程序?你遇到的问题是 参数传递,而不是 Windows shell 或 Python 本身的问题...

最后,就像 mattkemp 所说的那样,我建议你使用标准输入来读取多行参数,避免使用命令行技巧。


0

不确定Windows命令行是否可行,但以下内容是否可行?

> python myscript.py "This is a string\nIt has multiple lines\there are three total"

..或者..

> python myscript.py "This is a string\
It has [...]\
there are [...]"

如果没有的话,我建议安装Cygwin并使用一个理智的shell!

首先,cmd 命令行不使用 \ 作为转义字符,而是使用 ^。此外,^n 只会产生字面上的 n,因为 ^ 只能用于转义其他特殊字符,但它无法生成特殊字符,如 \n、\r 等。 - Joey

0
你尝试过将多行文本设置为变量,然后将其扩展传递到脚本中吗?例如:
set Text="This is a string
It has multiple lines
there are three total"
python args.py %Text%

或者,你可以从标准输入中读取而不是读取参数。

import sys

for line in iter(sys.stdin.readline, ''):
    print line

在Linux上,您可以将多行文本导入到args.py的标准输入中。

$ <生成文本的命令> | python args.py


似乎完全不起作用。无论是直接从Windows命令行还是从批处理文件中执行都不行。 - skrebbel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接