簡體   English   中英

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>

我認為問題出在類型輸出的<>中,一種解決方法? 提前致謝。

解:

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'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM