[英]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.