Kaydet (Commit) c79461b1 authored tarafından Collin Winter's avatar Collin Winter

Partial py3k-ification of Doc/library/: convert has_key references into either…

Partial py3k-ification of Doc/library/: convert has_key references into either 'k in d' or __contains__; normalize raise statements; convert print statements into print function calls.
üst 2ac01213
...@@ -105,6 +105,11 @@ Once instantiated, hash, btree and record objects support the same methods as ...@@ -105,6 +105,11 @@ Once instantiated, hash, btree and record objects support the same methods as
dictionaries. In addition, they support the methods listed below. dictionaries. In addition, they support the methods listed below.
.. describe:: key in bsddbobject
Return ``True`` if the DB file contains the argument as a key.
.. method:: bsddbobject.close() .. method:: bsddbobject.close()
Close the underlying file. The object can no longer be accessed. Since there Close the underlying file. The object can no longer be accessed. Since there
...@@ -119,11 +124,6 @@ dictionaries. In addition, they support the methods listed below. ...@@ -119,11 +124,6 @@ dictionaries. In addition, they support the methods listed below.
returned is different for different file formats. returned is different for different file formats.
.. method:: bsddbobject.has_key(key)
Return ``1`` if the DB file contains the argument as a key.
.. method:: bsddbobject.set_location(key) .. method:: bsddbobject.set_location(key)
Set the cursor to the item indicated by *key* and return a tuple containing the Set the cursor to the item indicated by *key* and return a tuple containing the
...@@ -169,7 +169,8 @@ Example:: ...@@ -169,7 +169,8 @@ Example::
>>> import bsddb >>> import bsddb
>>> db = bsddb.btopen('/tmp/spam.db', 'c') >>> db = bsddb.btopen('/tmp/spam.db', 'c')
>>> for i in range(10): db['%d'%i] = '%d'% (i*i) >>> for i in range(10):
... db[str(i)] = '%d' % (i*i)
... ...
>>> db['3'] >>> db['3']
'9' '9'
...@@ -186,7 +187,7 @@ Example:: ...@@ -186,7 +187,7 @@ Example::
>>> db.previous() >>> db.previous()
('1', '1') ('1', '1')
>>> for k, v in db.iteritems(): >>> for k, v in db.iteritems():
... print k, v ... print(k, v)
0 0 0 0
1 1 1 1
2 4 2 4
......
...@@ -91,11 +91,11 @@ various environment variables set according to the CGI standard). Since it may ...@@ -91,11 +91,11 @@ various environment variables set according to the CGI standard). Since it may
consume standard input, it should be instantiated only once. consume standard input, it should be instantiated only once.
The :class:`FieldStorage` instance can be indexed like a Python dictionary, and The :class:`FieldStorage` instance can be indexed like a Python dictionary, and
also supports the standard dictionary methods :meth:`has_key` and :meth:`keys`. also supports the standard dictionary methods :meth:`__contains__` and
The built-in :func:`len` is also supported. Form fields containing empty :meth:`keys`. The built-in :func:`len` is also supported. Form fields
strings are ignored and do not appear in the dictionary; to keep such values, containing empty strings are ignored and do not appear in the dictionary; to
provide a true value for the optional *keep_blank_values* keyword parameter when keep such values, provide a true value for the optional *keep_blank_values*
creating the :class:`FieldStorage` instance. keyword parameter when creating the :class:`FieldStorage` instance.
For instance, the following code (which assumes that the For instance, the following code (which assumes that the
:mailheader:`Content-Type` header and blank line have already been printed) :mailheader:`Content-Type` header and blank line have already been printed)
...@@ -103,7 +103,7 @@ checks that the fields ``name`` and ``addr`` are both set to a non-empty ...@@ -103,7 +103,7 @@ checks that the fields ``name`` and ``addr`` are both set to a non-empty
string:: string::
form = cgi.FieldStorage() form = cgi.FieldStorage()
if not (form.has_key("name") and form.has_key("addr")): if not ("name" in form and "addr" in form):
print "<H1>Error</H1>" print "<H1>Error</H1>"
print "Please fill in the name and addr fields." print "Please fill in the name and addr fields."
return return
......
...@@ -200,7 +200,7 @@ included in the mapping interface. ...@@ -200,7 +200,7 @@ included in the mapping interface.
No exception is raised if the named field isn't present in the headers. No exception is raised if the named field isn't present in the headers.
.. method:: Message.has_key(name) .. method:: Message.__contains__(name)
Return true if the message contains a header field named *name*, otherwise Return true if the message contains a header field named *name*, otherwise
return false. return false.
......
...@@ -122,10 +122,10 @@ This code is intended to be read, not executed. However, it does work ...@@ -122,10 +122,10 @@ This code is intended to be read, not executed. However, it does work
return m return m
def determine_parent(globals): def determine_parent(globals):
if not globals or not globals.has_key("__name__"): if not globals or not "__name__" in globals:
return None return None
pname = globals['__name__'] pname = globals['__name__']
if globals.has_key("__path__"): if "__path__" in globals:
parent = sys.modules[pname] parent = sys.modules[pname]
assert globals is parent.__dict__ assert globals is parent.__dict__
return parent return parent
...@@ -156,7 +156,7 @@ This code is intended to be read, not executed. However, it does work ...@@ -156,7 +156,7 @@ This code is intended to be read, not executed. However, it does work
parent = None parent = None
q = import_module(head, qname, parent) q = import_module(head, qname, parent)
if q: return q, tail if q: return q, tail
raise ImportError, "No module named " + qname raise ImportError("No module named " + qname)
def load_tail(q, tail): def load_tail(q, tail):
m = q m = q
...@@ -167,7 +167,7 @@ This code is intended to be read, not executed. However, it does work ...@@ -167,7 +167,7 @@ This code is intended to be read, not executed. However, it does work
mname = "%s.%s" % (m.__name__, head) mname = "%s.%s" % (m.__name__, head)
m = import_module(head, mname, m) m = import_module(head, mname, m)
if not m: if not m:
raise ImportError, "No module named " + mname raise ImportError("No module named " + mname)
return m return m
def ensure_fromlist(m, fromlist, recursive=0): def ensure_fromlist(m, fromlist, recursive=0):
...@@ -185,7 +185,7 @@ This code is intended to be read, not executed. However, it does work ...@@ -185,7 +185,7 @@ This code is intended to be read, not executed. However, it does work
subname = "%s.%s" % (m.__name__, sub) subname = "%s.%s" % (m.__name__, sub)
submod = import_module(sub, subname, m) submod = import_module(sub, subname, m)
if not submod: if not submod:
raise ImportError, "No module named " + subname raise ImportError("No module named " + subname)
def import_module(partname, fqname, parent): def import_module(partname, fqname, parent):
try: try:
......
...@@ -188,8 +188,7 @@ the corresponding message is subsequently removed. ...@@ -188,8 +188,7 @@ the corresponding message is subsequently removed.
subclass. subclass.
.. method:: Mailbox.has_key(key) .. method:: Mailbox.__contains__(key)
Mailbox.__contains__(key)
Return ``True`` if *key* corresponds to a message, ``False`` otherwise. Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
......
...@@ -260,7 +260,7 @@ A :class:`Message` instance has the following methods: ...@@ -260,7 +260,7 @@ A :class:`Message` instance has the following methods:
:class:`Message` instances also support a limited mapping interface. In :class:`Message` instances also support a limited mapping interface. In
particular: ``m[name]`` is like ``m.getheader(name)`` but raises :exc:`KeyError` particular: ``m[name]`` is like ``m.getheader(name)`` but raises :exc:`KeyError`
if there is no matching header; and ``len(m)``, ``m.get(name[, default])``, if there is no matching header; and ``len(m)``, ``m.get(name[, default])``,
``m.has_key(name)``, ``m.keys()``, ``m.values()`` ``m.items()``, and ``m.__contains__(name)``, ``m.keys()``, ``m.values()`` ``m.items()``, and
``m.setdefault(name[, default])`` act as expected, with the one difference ``m.setdefault(name[, default])`` act as expected, with the one difference
that :meth:`setdefault` uses an empty string as the default value. that :meth:`setdefault` uses an empty string as the default value.
:class:`Message` instances also support the mapping writable interface ``m[name] :class:`Message` instances also support the mapping writable interface ``m[name]
......
...@@ -131,7 +131,7 @@ object):: ...@@ -131,7 +131,7 @@ object)::
# such key) # such key)
del d[key] # delete data stored at key (raises KeyError del d[key] # delete data stored at key (raises KeyError
# if no such key) # if no such key)
flag = d.has_key(key) # true if the key exists flag = key in d # true if the key exists
klist = d.keys() # a list of all existing keys (slow!) klist = d.keys() # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware: # as d was opened WITHOUT writeback=True, beware:
......
...@@ -157,5 +157,5 @@ provided by this module. :: ...@@ -157,5 +157,5 @@ provided by this module. ::
except OSError as why: except OSError as why:
errors.extend((src, dst, str(why))) errors.extend((src, dst, str(why)))
if errors: if errors:
raise Error, errors raise Error(errors)
...@@ -144,7 +144,7 @@ be sent, and the handler raises an exception. :: ...@@ -144,7 +144,7 @@ be sent, and the handler raises an exception. ::
def handler(signum, frame): def handler(signum, frame):
print 'Signal handler called with signal', signum print 'Signal handler called with signal', signum
raise IOError, "Couldn't open device!" raise IOError("Couldn't open device!")
# Set the signal handler and a 5-second alarm # Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler) signal.signal(signal.SIGALRM, handler)
......
...@@ -157,10 +157,10 @@ Example:: ...@@ -157,10 +157,10 @@ Example::
callback(pathname) callback(pathname)
else: else:
# Unknown file type, print a message # Unknown file type, print a message
print 'Skipping %s' % pathname print('Skipping %s' % pathname)
def visitfile(file): def visitfile(file):
print 'visiting', file print('visiting', file)
if __name__ == '__main__': if __name__ == '__main__':
walktree(sys.argv[1], visitfile) walktree(sys.argv[1], visitfile)
......
...@@ -1032,8 +1032,8 @@ formats in the string *must* include a parenthesised mapping key into that ...@@ -1032,8 +1032,8 @@ formats in the string *must* include a parenthesised mapping key into that
dictionary inserted immediately after the ``'%'`` character. The mapping key dictionary inserted immediately after the ``'%'`` character. The mapping key
selects the value to be formatted from the mapping. For example:: selects the value to be formatted from the mapping. For example::
>>> print '%(language)s has %(#)03d quote types.' % \ >>> print('%(language)s has %(#)03d quote types.' %
{'language': "Python", "#": 2} {'language': "Python", "#": 2})
Python has 002 quote types. Python has 002 quote types.
In this case no ``*`` specifiers may occur in a format (since they require a In this case no ``*`` specifiers may occur in a format (since they require a
...@@ -1805,10 +1805,6 @@ types should support too): ...@@ -1805,10 +1805,6 @@ types should support too):
*default* is not given, it defaults to ``None``, so that this method never *default* is not given, it defaults to ``None``, so that this method never
raises a :exc:`KeyError`. raises a :exc:`KeyError`.
.. method:: dict.has_key(key)
``d.has_key(key)`` is equivalent to ``key in d``, but deprecated.
.. method:: dict.items() .. method:: dict.items()
Return a copy of the dictionary's list of ``(key, value)`` pairs. Return a copy of the dictionary's list of ``(key, value)`` pairs.
...@@ -1923,7 +1919,7 @@ Files have the following methods: ...@@ -1923,7 +1919,7 @@ Files have the following methods:
with open("hello.txt") as f: with open("hello.txt") as f:
for line in f: for line in f:
print line print(line)
In older versions of Python, you would have needed to do this to get the same In older versions of Python, you would have needed to do this to get the same
effect:: effect::
...@@ -1931,7 +1927,7 @@ Files have the following methods: ...@@ -1931,7 +1927,7 @@ Files have the following methods:
f = open("hello.txt") f = open("hello.txt")
try: try:
for line in f: for line in f:
print line print(line)
finally: finally:
f.close() f.close()
......
...@@ -45,7 +45,7 @@ Example usage:: ...@@ -45,7 +45,7 @@ Example usage::
output = StringIO.StringIO() output = StringIO.StringIO()
output.write('First line.\n') output.write('First line.\n')
print >>output, 'Second line.' print('Second line.', file=output)
# Retrieve file contents -- this will be # Retrieve file contents -- this will be
# 'First line.\nSecond line.\n' # 'First line.\nSecond line.\n'
...@@ -111,7 +111,7 @@ Example usage:: ...@@ -111,7 +111,7 @@ Example usage::
output = cStringIO.StringIO() output = cStringIO.StringIO()
output.write('First line.\n') output.write('First line.\n')
print >>output, 'Second line.' print('Second line.', file=output)
# Retrieve file contents -- this will be # Retrieve file contents -- this will be
# 'First line.\nSecond line.\n' # 'First line.\nSecond line.\n'
......
...@@ -284,11 +284,11 @@ A more realistic example would look like this:: ...@@ -284,11 +284,11 @@ A more realistic example would look like this::
try: try:
retcode = call("mycmd" + " myarg", shell=True) retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0: if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode print("Child was terminated by signal", -retcode, file=sys.stderr)
else: else:
print >>sys.stderr, "Child returned", retcode print("Child returned", retcode, file=sys.stderr)
except OSError as e: except OSError as e:
print >>sys.stderr, "Execution failed:", e print("Execution failed:", e, file=sys.stderr)
Replacing os.spawn\* Replacing os.spawn\*
......
...@@ -601,13 +601,13 @@ How to read a gzip compressed tar archive and display some member information:: ...@@ -601,13 +601,13 @@ How to read a gzip compressed tar archive and display some member information::
import tarfile import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz") tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar: for tarinfo in tar:
print tarinfo.name, "is", tarinfo.size, "bytes in size and is", print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="")
if tarinfo.isreg(): if tarinfo.isreg():
print "a regular file." print("a regular file.")
elif tarinfo.isdir(): elif tarinfo.isdir():
print "a directory." print("a directory.")
else: else:
print "something else." print("something else.")
tar.close() tar.close()
How to create a tar archive with faked information:: How to create a tar archive with faked information::
......
...@@ -234,5 +234,5 @@ A simple example illustrating typical use:: ...@@ -234,5 +234,5 @@ A simple example illustrating typical use::
tn.write("ls\n") tn.write("ls\n")
tn.write("exit\n") tn.write("exit\n")
print tn.read_all() print(tn.read_all())
...@@ -307,7 +307,7 @@ The :mod:`test.test_support` module defines the following functions: ...@@ -307,7 +307,7 @@ The :mod:`test.test_support` module defines the following functions:
Example use:: Example use::
with captured_stdout() as s: with captured_stdout() as s:
print "hello" print("hello")
assert s.getvalue() == "hello" assert s.getvalue() == "hello"
......
...@@ -64,8 +64,8 @@ indentation from strings that have unwanted whitespace to the left of the text. ...@@ -64,8 +64,8 @@ indentation from strings that have unwanted whitespace to the left of the text.
hello hello
world world
''' '''
print repr(s) # prints ' hello\n world\n ' print(repr(s)) # prints ' hello\n world\n '
print repr(dedent(s)) # prints 'hello\n world\n' print(repr(dedent(s))) # prints 'hello\n world\n'
.. class:: TextWrapper(...) .. class:: TextWrapper(...)
......
...@@ -135,7 +135,7 @@ In addition to these methods, lock objects can also be used via the ...@@ -135,7 +135,7 @@ In addition to these methods, lock objects can also be used via the
a_lock = thread.allocate_lock() a_lock = thread.allocate_lock()
with a_lock: with a_lock:
print "a_lock is locked while this executes" print("a_lock is locked while this executes")
**Caveats:** **Caveats:**
......
...@@ -683,7 +683,7 @@ exactly the same as the interval specified by the user. ...@@ -683,7 +683,7 @@ exactly the same as the interval specified by the user.
For example:: For example::
def hello(): def hello():
print "hello, world" print("hello, world")
t = Timer(30.0, hello) t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed t.start() # after 30 seconds, "hello, world" will be printed
...@@ -721,5 +721,5 @@ Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`, ...@@ -721,5 +721,5 @@ Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
some_rlock = threading.RLock() some_rlock = threading.RLock()
with some_rlock: with some_rlock:
print "some_rlock is locked while this executes" print("some_rlock is locked while this executes")
...@@ -196,13 +196,13 @@ attributes. :: ...@@ -196,13 +196,13 @@ attributes. ::
... pass ... pass
... """ ... """
>>> t = timeit.Timer(stmt=s) >>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
17.09 usec/pass 17.09 usec/pass
>>> s = """\ >>> s = """\
... if hasattr(str, '__bool__'): pass ... if hasattr(str, '__bool__'): pass
... """ ... """
>>> t = timeit.Timer(stmt=s) >>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
4.85 usec/pass 4.85 usec/pass
>>> s = """\ >>> s = """\
... try: ... try:
...@@ -211,13 +211,13 @@ attributes. :: ...@@ -211,13 +211,13 @@ attributes. ::
... pass ... pass
... """ ... """
>>> t = timeit.Timer(stmt=s) >>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
1.97 usec/pass 1.97 usec/pass
>>> s = """\ >>> s = """\
... if hasattr(int, '__bool__'): pass ... if hasattr(int, '__bool__'): pass
... """ ... """
>>> t = timeit.Timer(stmt=s) >>> t = timeit.Timer(stmt=s)
>>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000))
3.15 usec/pass 3.15 usec/pass
To give the :mod:`timeit` module access to functions you define, you can pass a To give the :mod:`timeit` module access to functions you define, you can pass a
...@@ -225,12 +225,10 @@ To give the :mod:`timeit` module access to functions you define, you can pass a ...@@ -225,12 +225,10 @@ To give the :mod:`timeit` module access to functions you define, you can pass a
def test(): def test():
"Stupid test function" "Stupid test function"
L = [] L = [i for i in range(100)]
for i in range(100):
L.append(i)
if __name__=='__main__': if __name__=='__main__':
from timeit import Timer from timeit import Timer
t = Timer("test()", "from __main__ import test") t = Timer("test()", "from __main__ import test")
print t.timeit() print(t.timeit())
...@@ -505,7 +505,7 @@ Tix Commands ...@@ -505,7 +505,7 @@ Tix Commands
import Tix import Tix
root = Tix.Tk() root = Tix.Tk()
print root.tix_configure() print(root.tix_configure())
.. method:: tixCommand.tix_configure([cnf,] **kw) .. method:: tixCommand.tix_configure([cnf,] **kw)
......
...@@ -184,7 +184,7 @@ A Simple Hello World Program ...@@ -184,7 +184,7 @@ A Simple Hello World Program
class Application(Frame): class Application(Frame):
def say_hi(self): def say_hi(self):
print "hi there, everyone!" print("hi there, everyone!")
def createWidgets(self): def createWidgets(self):
self.QUIT = Button(self) self.QUIT = Button(self)
...@@ -441,7 +441,7 @@ back will contain the name of the synonym and the "real" option (such as ...@@ -441,7 +441,7 @@ back will contain the name of the synonym and the "real" option (such as
Example:: Example::
>>> print fred.config() >>> print(fred.config())
{'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')} {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
Of course, the dictionary printed will include all the options available and Of course, the dictionary printed will include all the options available and
...@@ -560,8 +560,8 @@ For example:: ...@@ -560,8 +560,8 @@ For example::
self.print_contents) self.print_contents)
def print_contents(self, event): def print_contents(self, event):
print "hi. contents of entry is now ---->", \ print("hi. contents of entry is now ---->",
self.contents.get() self.contents.get())
The Window Manager The Window Manager
...@@ -633,7 +633,7 @@ callback ...@@ -633,7 +633,7 @@ callback
This is any Python function that takes no arguments. For example:: This is any Python function that takes no arguments. For example::
def print_it(): def print_it():
print "hi there" print("hi there")
fred["command"] = print_it fred["command"] = print_it
color color
......
...@@ -147,12 +147,12 @@ module. :: ...@@ -147,12 +147,12 @@ module. ::
try: try:
exec(source, envdir) exec(source, envdir)
except: except:
print "Exception in user code:" print("Exception in user code:")
print '-'*60 print("-"*60)
traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout)
print '-'*60 print("-"*60)
envdir = {} envdir = {}
while 1: while True:
run_user_code(envdir) run_user_code(envdir)
...@@ -438,14 +438,14 @@ containing parameters:: ...@@ -438,14 +438,14 @@ containing parameters::
>>> import urllib >>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.read() >>> print(f.read())
The following example uses the ``POST`` method instead:: The following example uses the ``POST`` method instead::
>>> import urllib >>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read() >>> print(f.read())
The following example uses an explicitly specified HTTP proxy, overriding The following example uses an explicitly specified HTTP proxy, overriding
environment settings:: environment settings::
......
...@@ -834,7 +834,7 @@ it:: ...@@ -834,7 +834,7 @@ it::
>>> import urllib2 >>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/') >>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read(100) >>> print(f.read(100))
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<?xml-stylesheet href="./css/ht2html <?xml-stylesheet href="./css/ht2html
...@@ -846,7 +846,7 @@ installation supports SSL. :: ...@@ -846,7 +846,7 @@ installation supports SSL. ::
>>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi', >>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
... data='This data is passed to stdin of the CGI') ... data='This data is passed to stdin of the CGI')
>>> f = urllib2.urlopen(req) >>> f = urllib2.urlopen(req)
>>> print f.read() >>> print(f.read())
Got Data: "This data is passed to stdin of the CGI" Got Data: "This data is passed to stdin of the CGI"
The code for the sample CGI used in the above example is:: The code for the sample CGI used in the above example is::
...@@ -854,7 +854,7 @@ The code for the sample CGI used in the above example is:: ...@@ -854,7 +854,7 @@ The code for the sample CGI used in the above example is::
#!/usr/bin/env python #!/usr/bin/env python
import sys import sys
data = sys.stdin.read() data = sys.stdin.read()
print 'Content-type: text-plain\n\nGot Data: "%s"' % data print('Content-type: text-plain\n\nGot Data: "%s"' % data)
Use of Basic HTTP Authentication:: Use of Basic HTTP Authentication::
......
...@@ -236,7 +236,7 @@ If the referent no longer exists, calling the reference object returns ...@@ -236,7 +236,7 @@ If the referent no longer exists, calling the reference object returns
:const:`None`:: :const:`None`::
>>> del o, o2 >>> del o, o2
>>> print r() >>> print(r())
None None
Testing that a weak reference object is still live should be done using the Testing that a weak reference object is still live should be done using the
...@@ -247,9 +247,9 @@ a reference object should follow this pattern:: ...@@ -247,9 +247,9 @@ a reference object should follow this pattern::
o = r() o = r()
if o is None: if o is None:
# referent has been garbage collected # referent has been garbage collected
print "Object has been deallocated; can't frobnicate." print("Object has been deallocated; can't frobnicate.")
else: else:
print "Object is still live!" print("Object is still live!")
o.do_something_useful() o.do_something_useful()
Using a separate test for "liveness" creates race conditions in threaded Using a separate test for "liveness" creates race conditions in threaded
......
...@@ -244,7 +244,7 @@ request. (E.g., using the :func:`shift_path_info` function from ...@@ -244,7 +244,7 @@ request. (E.g., using the :func:`shift_path_info` function from
from wsgiref.simple_server import make_server, demo_app from wsgiref.simple_server import make_server, demo_app
httpd = make_server('', 8000, demo_app) httpd = make_server('', 8000, demo_app)
print "Serving HTTP on port 8000..." print("Serving HTTP on port 8000...")
# Respond to requests until process is killed # Respond to requests until process is killed
httpd.serve_forever() httpd.serve_forever()
......
...@@ -272,5 +272,5 @@ Here is an example of how you would catch one of these exceptions:: ...@@ -272,5 +272,5 @@ Here is an example of how you would catch one of these exceptions::
try: try:
p.pack_double(8.01) p.pack_double(8.01)
except xdrlib.ConversionError as instance: except xdrlib.ConversionError as instance:
print 'packing the double failed:', instance.msg print('packing the double failed:', instance.msg)
...@@ -278,10 +278,10 @@ elements with no subelements will test as ``False``. :: ...@@ -278,10 +278,10 @@ elements with no subelements will test as ``False``. ::
element = root.find('foo') element = root.find('foo')
if not element: # careful! if not element: # careful!
print "element not found, or element has no subelements" print("element not found, or element has no subelements")
if element is None: if element is None:
print "element not found" print("element not found")
.. _elementtree-elementtree-objects: .. _elementtree-elementtree-objects:
......
...@@ -42,7 +42,7 @@ or as base classes. ...@@ -42,7 +42,7 @@ or as base classes.
will be wrapped in double-quotes. The resulting string can be used directly will be wrapped in double-quotes. The resulting string can be used directly
as an attribute value:: as an attribute value::
>>> print "<element attr=%s>" % quoteattr("ab ' cd \" ef") >>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd &quot; ef"> <element attr="ab ' cd &quot; ef">
This function is useful when generating attribute values for HTML or any SGML This function is useful when generating attribute values for HTML or any SGML
......
...@@ -371,12 +371,12 @@ Example of Client Usage ...@@ -371,12 +371,12 @@ Example of Client Usage
# server = ServerProxy("http://localhost:8000") # local server # server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://betty.userland.com") server = ServerProxy("http://betty.userland.com")
print server print(server)
try: try:
print server.examples.getStateName(41) print(server.examples.getStateName(41))
except Error as v: except Error as v:
print "ERROR", v print("ERROR", v)
To access an XML-RPC server through a proxy, you need to define a custom To access an XML-RPC server through a proxy, you need to define a custom
transport. The following example, written by NoboNobo, shows how: transport. The following example, written by NoboNobo, shows how:
...@@ -404,5 +404,5 @@ transport. The following example, written by NoboNobo, shows how: ...@@ -404,5 +404,5 @@ transport. The following example, written by NoboNobo, shows how:
p = ProxiedTransport() p = ProxiedTransport()
p.set_proxy('proxy-server:8080') p.set_proxy('proxy-server:8080')
server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p) server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
print server.currentTime.getCurrentTime() print(server.currentTime.getCurrentTime())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment