使用 python 的 wget 调用中的 KeyError

KeyError in a wget call using python

我正在 python 脚本中执行一些 wget 调用,我在其中发出一些 PUT 方法来发送一些命令,但是当 python 正在解析我想发送的 wget 命令时,它报告 wget 调用中变量的 KeyError。

我创建的命令是

wget = "wget --http-user={user} --http-password={password} --header='Accept:application/json' --header='Content-Type:application/json' --method=PUT --body-data='{'mode':'{bodyD}'}' -O- http://{IPaddress}/api/{v}/{cm}" .format(user=usr,password=pswd,IPaddress=node,v=version,bodyD=bodyData,cm=Command)

发送该命令时,KeyError 是 "KeyError:'mode'"。错误来自什么?我是否必须转义 "mode" 这个词因为它是保留的?

提前致谢,

此致,

按照 、

中的建议使用双 {{ }}

此外,BodyData 通常是 JSON,这可能需要双引号。

usr = "test"
pswd = "test"
node = "test"
version = "test"
bodyData = "test"
Command = "test"
wget = """wget --http-user={user} --http-password={password} --header='Accept:application/json' --header='Content-Type:application/json' --method=PUT --body-data='{{"mode":"{bodyD}"}}' -O- http://{IPaddress}/api/{v}/{cm}""".format(user=usr,password=pswd,IPaddress=node,v=version,bodyD=bodyData,cm=Command)

print wget

日志:

> python test.py
wget --http-user=test --http-password=test --header='Accept:application/json' --header='Content-Type:application/json' --method=PUT --body-data='{"mode":"test"}' -O- http://test/api/test/test

用双 {{ }} 大括号试一下:

wget = "wget --http-user={user} --http-password={password} --header='Accept:application/json' --header='Content-Type:application/json' --method=PUT --body-data='{{'mode':'{bodyD}'}}' -O- http://{IPaddress}/api/{v}/{cm}" .format(user=usr,password=pswd,IPaddress=node,v=version,bodyD=bodyData,cm=Command)

我试过用itsneo的回复,没用。然而,这给了我一个提示,并把花括号加倍。

所以这个命令确实有效

wget = "wget --http-user={user} --http-password={password} --header='Accept:application/json' --header='Content-Type:application/json' --method=PUT --body-data='{{mode:{bodyD}}}' -O- http://{IPaddress}/api/{v}/{cm}" .format(user=usr,password=pswd,IPaddress=node,v=version,bodyD=bodyData,cm=Command)