I have a very stupid problem, i'm trying to print the type of a variable direct to the browser, but the browser skips this action, here an example:
#!/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>"
The browser response is:
a = 1
going to print
printing
printed
v = None
going to print
printing
printed
f = ll
going to print
printing
printed
Desired response is:
a = 1
going to print
printing "int"
printed
v = None
going to print
printing "boolean"
printed
f = ll
going to print
printing "str"
printed
source code:
<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>
I think the problem is in <> of type output, a way to solve this? Thanks in advance.
SOLUTION:
cgi.escape("printing %s" % a, "<br>")
Your browser doesn't show the <type 'int'>
brackets as it thinks it's an HTML element:
In [1]: a = type(1)
In [2]: print a
<type 'int'>
In [3]: print "printing %s" % a
printing <type 'int'>
You can either view the source of your page where you should see the output or you need to escape the <
and >
brackets, for example like this:
In [4]: import cgi
In [5]: print cgi.escape("printing %s" % a)
printing <type 'int'>
You are essentially printing the type object: a = type(value)
, which will print <type 'int'>
. The browser will process it as a tag. To get your expected output try using the following:
a = type(value).__name__
The type object has an attribute called __name__
which can stores the string value of the type. Example:
>>> # Expected output
>>> type(1).__name__
>>> 'int'
>>> # Unexpected output
>>> type(1)
>>> <type 'int'>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.