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

10 投票
6 回答
14037 浏览
提问于 2025-04-15 11:07

我有一个简单的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:感谢大家的好建议。看起来这可能不太可行。我不能使用其他的命令行,因为我实际上是想从另一个程序中调用这个脚本,而这个程序似乎在后台使用的是Windows命令行。

6 个回答

1

这是我唯一能用的方法:

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

对我来说,Johannes的解决方案在第一行结束时调用了python解释器,所以我没有机会传递额外的行。

但是你说你是从另一个进程调用python脚本,而不是从命令行。那么为什么不试试dbr的解决方案呢?这个方法在我用Ruby脚本时有效:

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

你是用什么语言来调用python脚本的?你遇到的问题是关于参数传递的,不是windows命令行的问题,也不是python的问题……

最后,正如mattkemp所说,我也建议你使用标准输入来读取你的多行参数,这样可以避免命令行的复杂操作。

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
4

我知道这个讨论已经有点时间了,但我在解决类似问题时碰到了它,其他人可能也会遇到,所以我想分享一下我是怎么解决的。

这个方法在Windows XP专业版上是有效的,使用的是Zack的代码,保存在一个叫做
"C:\Scratch\test.py"的文件里:

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的解决方案更容易理解。

撰写回答