我有一個這樣的字串:
/acommand foo='bar' msg='Hello World!' -debugMode
或者像這樣:
/acommand
foo='bar'
msg='Hello, World!'
-debugMode
如何將此字串決議為字典和如下串列:
{"command": "/acommand", "foo": "bar", "msg": "Hello World!"}
["-debugMode"]
我試圖用來string.split決議它,但似乎不可行。
argparse 似乎它是為命令列界面而生的,所以它不適用。
如何使用 Python 實作這一目標?謝謝!
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
s = "/acommand foo='bar' msg='Hello World!' -debugMode"
debug = [s.split(" ")[-1]]
s_ = "command=" ' '.join(s.split(" ")[:-1]).replace("'","")
d = dict(x.split("=") for x in s_.split(" ",2))
print (d)
print (debug)
{'command': '/acommand', 'foo': 'bar', 'msg': 'Hello World!'},
['-除錯模式']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354806.html
