2014-01-30 128 views
0

我试图创建一个Python CGI脚本的HTML表单。我不明白蟒蛇`打印“”“'

script_name=os.environ.get('SCRIPT_NAME', '') 

form = cgi.FieldStorage() 
message = form.getvalue("message", "(no message)") 

print """ 

    <p>Previous message: %s</p> 

    <p>form 

    <form method="post" action="%s"> 
    <p>message: <input type="text" name="message"/></p> 
    </form> 

</body> 

</html> 
""" % cgi.escape(message), script_name 

以上当然是行不通的。我是假的印象是, 整个print """ blah blah %s ...""" % string_var工作像C的printf功能 那么,要我想在这里做

我在浏览器中收到此错误信息:?

Traceback (most recent call last): 
    File "/usr/lib/cgi-bin/hello.py", line 45, in <module> 
    """ % cgi.escape(message), script_name 
TypeError: not enough arguments for format string 
+1

居然会发生什么?你有错误信息吗?如果是这样,你能把它展示给我们吗? – user2357112

+4

将括号内的格式化参数包装在内:) – mhlester

+1

如果没有括号,Python会认为您想要打印两样东西:一个格式参数为单个字符串,另一个为第二个变量。 – jayelm

回答

2

您需要将括号中的格式参数包装起来。

print """ %s %s 
do re me fa so la ti do 
""" % (arg1(arg), arg2) 
3
print 'blah' % x, y 

不被解释为

print 'blah' % (x, y) 

而是围绕cgi.escape(message), script_name而是作为

print ('blah' % x), y 

认沽括号元组为第二个参数传递给%。顺便提一句,这是您可能希望str.format方法优于%的原因之一。

2

当你的代码执行,这种情况发生的第一件事就是它计算表达式

long_string % cgi.escape(message) 

因为有长串的两个键,但只有一个在%操作者的另一侧值,这是您看到的TypeError失败。

的解决方案是在括号包裹两个值,所以第二个操作数被解释为一个元组:

long_string % (cgi.escape(message), script_name) 
+0

更好的解决方案是使用新的'.format'方法,如果使用它,这个错误永远不会发生。 – SethMMorton

+0

@Steh interesting。我可以在哪里学到更多关于.format? –

+0

[Format string syntax](http://docs.python。组织/ 2 /库/ string.html#格式串的语法) – SethMMorton