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

Python 在Windows中将多行字符串作为参数传递给脚本,python,windows,string,dos,batch-file,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"

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

只需将参数括在引号中:

$ 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

不确定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并使用sane外壳

以下方法可能有效:

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

您是否尝试过将多行文本设置为变量,然后将其扩展传递到脚本中。例如:

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

这是唯一适合我的东西:

C:\> python a.py This" "is" "a" "string^
More?
More? It" "has" "multiple" "lines^
More?
More? There" "are" "three" "total
对于我来说,在第一行末尾调用python解释器,因此我没有机会传递其他行

但是您说您是从另一个进程调用python脚本,而不是从命令行。那你为什么不用呢?这对我来说是一个Ruby脚本:

puts `python a.py "This is a string\nIt has multiple lines\nThere are three total"`
你用什么语言编写程序来调用python脚本?您遇到的问题是参数传递,而不是windows shell,也不是Python


最后,如前所述,我还建议您使用标准输入来读取多行参数,避免使用命令行魔法。

我知道这个线程非常古老,但我在尝试解决类似问题时遇到了它,其他人也可能遇到,所以让我向您展示我是如何解决它的

这至少适用于Windows XP Pro,Zack的代码保存在一个名为
“C:\Scratch\test.py”:


这比上面Romulo的解决方案更具可读性。

我不明白-您现在的解决方案是否有效?您应该按“\n”拆分,并事先删除“\r”,以提高平台兼容性。
bash
是否将carraige返回放在它的参数中?(不确定)。您根本不应该使用字符串模块。这一行应该是
lines=multiline.splitlines()
所有好的建议。到目前为止,我使用python的总经验大约是一个小时。首先,cmd不使用\作为转义字符,而是使用^。其次,^n只会产生一个文本n,因为^n只能用于转义其他特殊字符,但它没有生成特殊字符的功能,如\n、\r等。这使我可以有效地跨越多行字符串,但仍然没有“换行符”字符串中的字符。在这种情况下,空行很重要。至少echo可以输出多行代码,但目前我无法在这里进行测试。如果所有其他方法都失败,请使用其他人建议的管道解决方案。至少,通过stdin传递多行代码是没有问题的。似乎根本不起作用。不是直接从windows命令行,也不是从批处理文件。
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>