我正在尝试从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&#39 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
答案 0 :(得分:3)
print 'blah' % x, y
不被解释为
print 'blah' % (x, y)
而是
print ('blah' % x), y
将括号括在cgi.escape(message), script_name
左右,将元组作为第二个参数传递给%
。顺便说一句,这是您可能希望str.format
方法优先于%
的原因之一。
答案 1 :(得分:2)
您需要将格式参数包装在括号中。
print """ %s %s
do re me fa so la ti do
""" % (arg1(arg), arg2)
答案 2 :(得分:2)
当你的代码执行时,首先发生的是评估表达式
long_string % cgi.escape(message)
由于长字符串中有两个键,但%
运算符的另一侧只有一个值,因此您看到的TypeError
失败了。
解决方案是将两个值都包装在括号中,因此第二个操作数被解释为元组:
long_string % (cgi.escape(message), script_name)