python CGI打印功能

时间:2015-05-24 13:08:05

标签: python cgi

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

#!/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>

我认为问题出在&lt;&gt;类型输出,一种解决这个问题的方法? 提前谢谢。

解决方案:

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

2 个答案:

答案 0 :(得分:1)

您的浏览器没有显示<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;

答案 1 :(得分:0)

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

a = type(value).__name__

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

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