0

我正在尝试从字典中打印以填充另一个脚本。我不断收到“行继续字符后的意外字符”。我不知道为什么

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")
4

2 回答 2

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)
于 2013-10-11T18:47:09.363 回答
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")

你真的想在这里使用一些字符串格式,以及一个三引号的原始字符串来减少所有这些反斜杠:

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]))
于 2013-10-11T18:45:06.750 回答