11.5.20 例

以下の例では、 python.org のメインページを取得して、その最初の 100 バイト分を表示します:

>>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read(100)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?xml-stylesheet href="./css/ht2html

今度は CGI の標準入力にデータストリームを送信し、CGI が返すデータ を読み出します:

>>> import urllib2
>>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
...                       data='This data is passed to stdin of the CGI')
>>> f = urllib2.urlopen(req)
>>> print f.read()
Got Data: "This data is passed to stdin of the CGI"

上の例で使われているサンプルの CGI は以下のようになっています:

#!/usr/bin/env python
import sys
data = sys.stdin.read()
print 'Content-type: text-plain\n\nGot Data: "%s"' % data
ご意見やご指摘をお寄せになりたい方は、 このドキュメントについて... をご覧ください。