繁体   English   中英

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

[英]Passing a multi-line string as an argument to a script in Windows

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

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

这至少在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解决方案更具可读性。

只需将参数括在引号中:

$ 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

以下可能有效:

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

这是唯一对我有用的东西:

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 shell,而不是Python ...

最后,正如mattkemp所说,我还建议你使用标准输入来读取你的多行参数,避免命令行魔术。

不确定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并使用理智的外壳!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM