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

时间:2009-04-14 19:37:10

标签: python windows string dos batch-file

我有一个简单的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命令行。

6 个答案:

答案 0 :(得分: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 :(得分:2)

我知道这个帖子已经很老了,但我在试图解决类似的问题时遇到了它,而其他人也可能会这样,所以让我告诉你我是如何解决它的。

这至少在Windows XP Pro上有效,Zack的代码在一个名为
的文件中 “C:\划痕\ 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解决方案更具可读性。

答案 2 :(得分:1)

以下可能有效:

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

答案 3 :(得分: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所说,我还建议您使用标准输入来读取多行参数,避免命令行魔术。

答案 4 :(得分: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并使用理智的外壳!

答案 5 :(得分: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的标准输入。

$< command-that-produce-text> | python args.py

相关问题