试图打印字典密钥对

时间:2013-10-11 18:41:12

标签: python dictionary

我正在尝试从字典中打印以填充另一个脚本。我一直得到“线后续角色的意外角色”。我不知道为什么

mydic = {"printer1": "printserver1", "printer2": "printserver2"}

for key in mydic.keys():
  print ("For /F \"Tokens=4 delims=\\\" %%I In ('reg query HKCU\\Printers\\Connections       ^|find /I \"" + key + "\"') Do If \"%%I\"==\",,"+ mydic[key] +"," + key + "\" goto :REMOVE" + \n + "goto :SKIP" + \n + ":REMOVE" + \n + "RUNDLL32 printui.dll,PrintUIEntry /n \\\\"+ mydic[key] +"\\" + key + " /dn" + \n + ":SKIP")

2 个答案:

答案 0 :(得分:8)

通过使用多行字符串,简化了这一点,因此它不是全部一行,更具可读性,换行符自动成为字符串的一部分:

mydic = {"printer1": "printserver1", "printer2": "printserver2"}

template = r"""
FOR /F in blah blah blah
    do something with {key}
    with the value of {value}
    blah blah blah
END FOR
"""

for key, value in mydic.iteritems():
    print template.format(key=key, value=value)

答案 1 :(得分:2)

\n换行符作为字符串的一部分:

print ("For /F \"Tokens=4 delims=\\\" %%I In ('reg query HKCU\\Printers\\Connections       ^|find /I \"" +
       key + "\"') Do If \"%%I\"==\",," + mydic[key] + "," + key + 
       "\" goto :REMOVE\ngoto :SKIP\n:REMOVERUNDLL32 printui.dll,PrintUIEntry /n \\\" +
       mydic[key] +"\\" + key + " /dn\n:SKIP")

你真的想在这里使用一些string formatting,再加上三引号的原始字符串来减少所有这些反斜杠:

template = r"""For /F "Tokens=4 delims=\" %%I In ('reg query HKCU\Printers\Connections       ^|find /I "{0}"') Do If "%%I"==",,"{1},{0}" goto :REMOVE
goto :SKIP
:REMOVERUNDLL32 printui.dll,PrintUIEntry /n \{1}\{0} /dn
:SKIP"""

for key in mydic:
    print(template.format(key, mydic[key]))