0

私は Mark Lutz のProgramming Python 3rd editionを読んでいますが、質問に困惑しています:type('something')常に空の文字列になります。

誰かが親切にこれを説明できますか?

コンテキスト情報:

スクリプトに 1 行追加します$CODEROOT\pp3e\Internet\Web\cgi-bin\tutor0.py

#!/usr/bin/python
#######################################################
# runs on the server, prints html to create a new page;
# url=http://localhost/cgi-bin/tutor0.py
#######################################################

print "Content-type: text/html\n"
print "<TITLE>CGI 101</TITLE>"
print "<H1>A First CGI script</H1>"
print '<p>[%s]'%type('apple') # ★ I add this line
print "<P>Hello, CGI World!</P>"

追加された行は、ブラウザ[<type 'str'>]で見たいのですが、実際には が表示されます[]

ここに画像の説明を入力

HTTP サーバーを起動するための Python は次の場所にあります。$CODEROOT\pp3e\Internet\Web\webserver.py

#########################################################################
# implement HTTP web server in Python which knows how to serve HTML
# pages and run server side CGI scripts;  serves files/scripts from
# the current working dir and port 80, unless command-line args;
# python scripts must be stored in webdir\cgi-bin or webdir\htbin;
# more than one of these may be running on the same machine to serve
# from different directories, as long as they listen on different ports;
#########################################################################

webdir = '.'   # where your html files and cgi-bin script directory live
port   = 80    # http://servername/ if 80, else use http://servername:xxxx/

import os, sys
from BaseHTTPServer import HTTPServer
from CGIHTTPServer  import CGIHTTPRequestHandler

if len(sys.argv) > 1: webdir = sys.argv[1]             # command-line args
if len(sys.argv) > 2: port   = int(sys.argv[2])        # else dafault ., 80
print 'webdir "%s", port %s' % (webdir, port)

# hack for Windows: os.environ not propogated
# to subprocess by os.popen2, force in-process
if sys.platform[:3] == 'win':
    CGIHTTPRequestHandler.have_popen2 = False
    CGIHTTPRequestHandler.have_popen3 = False          # emulate path after fork
    sys.path.append('cgi-bin')                         # else only adds my dir

os.chdir(webdir)                                       # run in html root dir
srvraddr = ("", port)                                  # my hostname, portnumber
srvrobj  = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()                                # serve clients till exit

私の環境:

  • パイソン 2.7
  • ウィンドウズ 7 x64
4

1 に答える 1

6

おそらく、山かっこ<type 'str'>が原因で出力が HTML として扱われるためです。

変更してみてください:

print '<p>[%s]'%type('apple') # ★ I add this line

の中へ:

hstr = "%s"%type('apple')
hstr = hstr.replace('<','&lt;').replace('>','&gt;')
print '<p>[%s]'%hstr
于 2012-08-06T02:42:55.703 に答える