python CGI打印函数

python CGI print function

我有一个非常愚蠢的问题,我试图将变量的类型直接打印到浏览器,但是浏览器跳过了这个动作,这里有一个例子:

#!/usr/bin/python
import cgi, cgitb;  cgitb.enable()


def print_keyword_args(**kwargs):

    # kwargs is a dict of the keyword args passed to the function
    for key, value in kwargs.iteritems():
        a =     type(value)
        print "<br>"        
        print "%s = %s" % (key, value), "<br>"
        print "going to print<br>"
        print "printing %s" % a, "<br>"
        print "printed<br>" 
        print "<br>"    

form = {'a': 1, "v": None, "f": "ll"}

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>form</title>"
print "</head>"
print "<body>"
print_keyword_args(**form)
print "</body>"
print "</html>"

浏览器响应为:

a = 1 
going to print
printing 
printed


v = None 
going to print
printing 
printed


f = ll 
going to print
printing 
printed

期望的回复是:

a = 1 
going to print 
printing "int"
printed


v = None 
going to print 
printing "boolean"
printed


f = ll 
going to print
printing  "str"
printed

源代码:

<html>
<head>
<title>locoooo</title>
</head>
<body>
hola
<br>
a = 1 <br>
going to print<br>
printing <type 'int'> <br>
printed<br>
<br>
<br>
v = None <br>
going to print<br>
printing <type 'NoneType'> <br>
printed<br>
<br>
<br>
f = ll <br>
going to print<br>
printing <type 'str'> <br>
printed<br>
<br>
</body>
</html>

我认为问题出在 <> of type output,有解决办法吗? 提前致谢。

解决方案:

cgi.escape("printing %s" % a, "<br>")

您的浏览器不显示 <type 'int'> 括号,因为它认为这是一个 HTML 元素:

In [1]: a = type(1)

In [2]: print a
<type 'int'>

In [3]: print "printing %s" % a
printing <type 'int'>

您可以查看您应该看到输出的页面源代码,或者您需要转义 <> 括号,例如:

In [4]: import cgi

In [5]: print cgi.escape("printing %s" % a)
printing &lt;type 'int'&gt;

您实际上是在打印类型对象:a = type(value),它将打印 <type 'int'>。浏览器会将其作为标签处理。要获得预期的输出,请尝试使用以下命令:

a = type(value).__name__

类型对象有一个名为__name__的属性,可以存储类型的字符串值。示例:

>>> # Expected output
>>> type(1).__name__
>>> 'int'
>>> # Unexpected output
>>> type(1)
>>> <type 'int'>