简体   繁体   中英

Python KeyError with Curly Braces

I want Python to run system commands of curl where I pass in some arguments. I want to also use -w "%{http_code}" to return the HTTP status code of the result (ie 200 , 302 , etc)

The command I currently have is

print os.popen('curl "{0}" -L -o /dev/null -s -w "%{http_code}"'.format("http://google.com")).read()

but this returns KeyError: 'http_code' and I presume its because the http_code is wrapped by curlybraces. How do I get around this?

Just double up the curly braces when passing to .format :

'curl "{0}" -L -o /dev/null -s -w "%{{http_code}}"'.format("http://google.com")

This escapes them and will produce %{http_code} in the resulting string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM