[英]Passing a command line argument to Python whos string contains a metacharacter
[英]Passing a string with spaces and newlines as command line argument python
我試圖在名為main.py
的 python 腳本中傳遞一個帶有空格和換行符的字符串作為命令行參數,但不確定是否可行。
我正在嘗試傳遞字符串'5 2\n 3 3 2\n 1 1 2'
並讓它完全像那樣出現在腳本中。 為此,我正在使用sys
和argv
:
命令行:
python main.py "5 2\n 3 3 2\n 1 1 2"
Python 腳本:
info_input = sys.argv[1]
然而,output 似乎是一個在換行符中添加了轉義字符的列表:
['5 2\\n 3 3 2\\n 1 1 2']
是否可以將此作為參數傳遞,並使 python 中的 output 顯示為:
"5 2\n 3 3 2\n 1 1 2"
非常感謝
編輯
print(info_input)
'5 2\n 3 3 2\n 1 1 2'
input_split = info_input.split(sep='\n')
print(input_split)
['5 2\\n 3 3 2\\n 1 1 2']
它沒有在此處的換行符上拆分,並且是整個事物的列表。
關於您問題的這兩點的一些澄清
我正在嘗試傳遞帶有空格和換行符的字符串
是否可以將此作為爭論傳遞,並使 python 中的 output 顯示為:
當您使用python main.py "5 2\n 3 3 2\n 1 1 2"
調用腳本時,您沒有傳遞實際的換行符。 這就是為什么你在你的字符串中得到\\n
, Python 是 escaping 那些\n
因為否則這意味着你的字符串確實有換行符。
您混淆了字符串的表示和字符串本身。 檢查這個關於repr
與str
的問題。
單獨打印字符串時打印效果很好,但打印列表時會顯示轉義字符,這解釋了為什么會得到不同的結果。
當你這樣做時:
input_split = info_input.split(sep='\n')
print(input_split)
您實際上並沒有拆分字符串,因為您的字符串不包含換行符( \n
),它包含轉義的換行符( \\n
)。
如果你真的想用換行符分割你的字符串,你可以這樣做:
input_split = info_input.split(sep='\\n')
print(input_split)
它輸出['5 2', ' 3 3 2', ' 1 1 2']
。
也就是說,如果您的目標是在程序中使用實際的換行符,您可以用換行符替換轉義的換行符:
import sys
info_input = sys.argv[1]
info_input_with_escaped_newlines = info_input
print("info_input_with_escaped_newlines as string", info_input_with_escaped_newlines)
print("info_input_with_escaped_newlines as list", [info_input_with_escaped_newlines])
info_input_with_newlines = info_input.replace('\\n', '\n')
print("info_input_with_newlines as string", info_input_with_newlines)
print("info_input_with_newlines as list", [info_input_with_newlines])
哪個輸出
> python as.py "5 2\n 3 3 2\n 1 1 2"
info_input_with_escaped_newlines as string 5 2\n 3 3 2\n 1 1 2
info_input_with_escaped_newlines as list ['5 2\\n 3 3 2\\n 1 1 2']
info_input_with_newlines as string 5 2
3 3 2
1 1 2
info_input_with_newlines as list ['5 2\n 3 3 2\n 1 1 2']
注意現在split
如何拆分字符串:
import sys
info_input = sys.argv[1].replace('\\n', '\n').split(sep='\n')
print(info_input)
輸出:
python as.py "5 2\n 3 3 2\n 1 1 2"
['5 2', ' 3 3 2', ' 1 1 2']
可能的繞過可能是string.replace()
。 你可以做'5 2NL 3 3 2NL 1 1 2'
然后info_input = sys.argv[1].replace("NL", "\n")
。 在您找到更好的方法之前,這可能是一個臨時解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.