8

I have a simple python script like so:

import sys

lines = sys.argv[1]

for line in lines.splitlines():
    print line

I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?

Of course, this works:

import sys

lines = """This is a string
It has multiple lines
there are three total"""

for line in lines.splitlines():
    print line

But I need to be able to process an argument line-by-line.

EDIT: This is probably more of a Windows command-line problem than a Python problem.

EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.

4

6 回答 6

4

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

这至少在 Windows XP Pro 上有效,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 的解决方案更具可读性。

于 2010-05-08T18:26:32.480 回答
2

Just enclose the argument in quotes:

$ 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
于 2009-04-14T19:44:13.980 回答
1

以下可能有效:

C:\> python something.py "This is a string^
More?
More? It has multiple lines^
More?
More? There are three total"
于 2009-04-14T20:47:10.803 回答
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 shell,不是 Python ......

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

于 2009-04-16T17:47:40.777 回答
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 并使用健全的外壳!

于 2009-04-14T20:46:04.580 回答
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 的标准输入。

$ <产生文本的命令> | 蟒蛇args.py

于 2009-04-14T20:49:39.300 回答