2009-04-14 162 views
5

我有一个简单的Python脚本,像这样:传递一个多行字符串作为参数传递给脚本在Windows

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 

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

编辑:这可能是一个比Python问题更多的Windows命令行问题。

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

+0

我不明白 - 你现在没有工作吗? – 2009-04-14 19:41:15

+0

您应该按“\ n”拆分并预先删除“\ r”以获得更好的平台兼容性。 `bash`是否将carraige返回到它的参数中? (不确定)。 – 2009-04-14 19:49:42

+0

根本不应该使用字符串模块。该行应该读取`lines = multiline.splitlines()` – 2009-04-14 19:55:58

回答

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 
+0

这可以从Windows命令行完成吗? – 2009-04-14 20:17:13

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和使用理智的外壳!

1

下可能的工作:

C:\> python something.py "This is a string^ 
More? 
More? It has multiple lines^ 
More? 
More? There are three total" 
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 > |蟒蛇args.py

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外壳程序,而不是与Python ...

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

2

我知道这个线程很旧,但我在试图解决类似问题时碰到它,而其他人可能也如此,所以让我告诉你我是如何解决它的。

这个工程至少在Windows XP专业版,与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> 

这一点更具可读性比罗密欧的解决方案上面。

相关问题