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()
Close the underlying file. The object can no longer be accessed. Since there
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)
Set the cursor to the item indicated by *key* and return a tuple containing the
>>> import bsddb
>>> 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']
'9'
>>> db.previous()
('1', '1')
>>> for k, v in db.iteritems():
- ... print k, v
+ ... print(k, v)
0 0
1 1
2 4
consume standard input, it should be instantiated only once.
The :class:`FieldStorage` instance can be indexed like a Python dictionary, and
-also supports the standard dictionary methods :meth:`has_key` and :meth:`keys`.
-The built-in :func:`len` is also supported. Form fields containing empty
-strings are ignored and do not appear in the dictionary; to keep such values,
-provide a true value for the optional *keep_blank_values* keyword parameter when
-creating the :class:`FieldStorage` instance.
+also supports the standard dictionary methods :meth:`__contains__` and
+:meth:`keys`. The built-in :func:`len` is also supported. Form fields
+containing empty strings are ignored and do not appear in the dictionary; to
+keep such values, provide a true value for the optional *keep_blank_values*
+keyword parameter when creating the :class:`FieldStorage` instance.
For instance, the following code (which assumes that the
:mailheader:`Content-Type` header and blank line have already been printed)
string::
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 "Please fill in the name and addr fields."
return
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 false.
return m
def determine_parent(globals):
- if not globals or not globals.has_key("__name__"):
+ if not globals or not "__name__" in globals:
return None
pname = globals['__name__']
- if globals.has_key("__path__"):
+ if "__path__" in globals:
parent = sys.modules[pname]
assert globals is parent.__dict__
return parent
parent = None
q = import_module(head, qname, parent)
if q: return q, tail
- raise ImportError, "No module named " + qname
+ raise ImportError("No module named " + qname)
def load_tail(q, tail):
m = q
mname = "%s.%s" % (m.__name__, head)
m = import_module(head, mname, m)
if not m:
- raise ImportError, "No module named " + mname
+ raise ImportError("No module named " + mname)
return m
def ensure_fromlist(m, fromlist, recursive=0):
subname = "%s.%s" % (m.__name__, sub)
submod = import_module(sub, subname, m)
if not submod:
- raise ImportError, "No module named " + subname
+ raise ImportError("No module named " + subname)
def import_module(partname, fqname, parent):
try:
subclass.
-.. method:: Mailbox.has_key(key)
- Mailbox.__contains__(key)
+.. method:: Mailbox.__contains__(key)
Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
:class:`Message` instances also support a limited mapping interface. In
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])``,
-``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
that :meth:`setdefault` uses an empty string as the default value.
:class:`Message` instances also support the mapping writable interface ``m[name]
# such key)
del d[key] # delete data stored at key (raises KeyError
# 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!)
# as d was opened WITHOUT writeback=True, beware:
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
- raise Error, errors
+ raise Error(errors)
def handler(signum, frame):
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
signal.signal(signal.SIGALRM, handler)
callback(pathname)
else:
# Unknown file type, print a message
- print 'Skipping %s' % pathname
+ print('Skipping %s' % pathname)
def visitfile(file):
- print 'visiting', file
+ print('visiting', file)
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)
dictionary inserted immediately after the ``'%'`` character. The mapping key
selects the value to be formatted from the mapping. For example::
- >>> print '%(language)s has %(#)03d quote types.' % \
- {'language': "Python", "#": 2}
+ >>> print('%(language)s has %(#)03d quote types.' %
+ {'language': "Python", "#": 2})
Python has 002 quote types.
In this case no ``*`` specifiers may occur in a format (since they require a
*default* is not given, it defaults to ``None``, so that this method never
raises a :exc:`KeyError`.
-.. method:: dict.has_key(key)
-
- ``d.has_key(key)`` is equivalent to ``key in d``, but deprecated.
-
.. method:: dict.items()
Return a copy of the dictionary's list of ``(key, value)`` pairs.
with open("hello.txt") as 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
effect::
f = open("hello.txt")
try:
for line in f:
- print line
+ print(line)
finally:
f.close()
output = StringIO.StringIO()
output.write('First line.\n')
- print >>output, 'Second line.'
+ print('Second line.', file=output)
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
output = cStringIO.StringIO()
output.write('First line.\n')
- print >>output, 'Second line.'
+ print('Second line.', file=output)
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
- print >>sys.stderr, "Child was terminated by signal", -retcode
+ print("Child was terminated by signal", -retcode, file=sys.stderr)
else:
- print >>sys.stderr, "Child returned", retcode
+ print("Child returned", retcode, file=sys.stderr)
except OSError as e:
- print >>sys.stderr, "Execution failed:", e
+ print("Execution failed:", e, file=sys.stderr)
Replacing os.spawn\*
import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
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():
- print "a regular file."
+ print("a regular file.")
elif tarinfo.isdir():
- print "a directory."
+ print("a directory.")
else:
- print "something else."
+ print("something else.")
tar.close()
How to create a tar archive with faked information::
tn.write("ls\n")
tn.write("exit\n")
- print tn.read_all()
+ print(tn.read_all())
Example use::
with captured_stdout() as s:
- print "hello"
+ print("hello")
assert s.getvalue() == "hello"
hello
world
'''
- print repr(s) # prints ' hello\n world\n '
- print repr(dedent(s)) # prints 'hello\n world\n'
+ print(repr(s)) # prints ' hello\n world\n '
+ print(repr(dedent(s))) # prints 'hello\n world\n'
.. class:: TextWrapper(...)
a_lock = thread.allocate_lock()
with a_lock:
- print "a_lock is locked while this executes"
+ print("a_lock is locked while this executes")
**Caveats:**
For example::
def hello():
- print "hello, world"
+ print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
some_rlock = threading.RLock()
with some_rlock:
- print "some_rlock is locked while this executes"
+ print("some_rlock is locked while this executes")
... pass
... """
>>> 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
>>> s = """\
... if hasattr(str, '__bool__'): pass
... """
>>> 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
>>> s = """\
... try:
... pass
... """
>>> 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
>>> s = """\
... if hasattr(int, '__bool__'): pass
... """
>>> 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
To give the :mod:`timeit` module access to functions you define, you can pass a
def test():
"Stupid test function"
- L = []
- for i in range(100):
- L.append(i)
+ L = [i for i in range(100)]
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
- print t.timeit()
+ print(t.timeit())
import Tix
root = Tix.Tk()
- print root.tix_configure()
+ print(root.tix_configure())
.. method:: tixCommand.tix_configure([cnf,] **kw)
class Application(Frame):
def say_hi(self):
- print "hi there, everyone!"
+ print("hi there, everyone!")
def createWidgets(self):
self.QUIT = Button(self)
Example::
- >>> print fred.config()
+ >>> print(fred.config())
{'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
Of course, the dictionary printed will include all the options available and
self.print_contents)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", \
- self.contents.get()
+ print("hi. contents of entry is now ---->",
+ self.contents.get())
The Window Manager
This is any Python function that takes no arguments. For example::
def print_it():
- print "hi there"
+ print("hi there")
fred["command"] = print_it
color
try:
exec(source, envdir)
except:
- print "Exception in user code:"
- print '-'*60
+ print("Exception in user code:")
+ print("-"*60)
traceback.print_exc(file=sys.stdout)
- print '-'*60
+ print("-"*60)
envdir = {}
- while 1:
+ while True:
run_user_code(envdir)
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> 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::
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> 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
environment settings::
>>> import urllib2
>>> 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">
<?xml-stylesheet href="./css/ht2html
>>> 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()
+ >>> print(f.read())
Got Data: "This data is passed to stdin of the CGI"
The code for the sample CGI used in the above example is::
#!/usr/bin/env python
import sys
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::
:const:`None`::
>>> del o, o2
- >>> print r()
+ >>> print(r())
None
Testing that a weak reference object is still live should be done using the
o = r()
if o is None:
# referent has been garbage collected
- print "Object has been deallocated; can't frobnicate."
+ print("Object has been deallocated; can't frobnicate.")
else:
- print "Object is still live!"
+ print("Object is still live!")
o.do_something_useful()
Using a separate test for "liveness" creates race conditions in threaded
from wsgiref.simple_server import make_server, 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
httpd.serve_forever()
try:
p.pack_double(8.01)
except xdrlib.ConversionError as instance:
- print 'packing the double failed:', instance.msg
+ print('packing the double failed:', instance.msg)
element = root.find('foo')
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:
- print "element not found"
+ print("element not found")
.. _elementtree-elementtree-objects:
will be wrapped in double-quotes. The resulting string can be used directly
as an attribute value::
- >>> print "<element attr=%s>" % quoteattr("ab ' cd \" ef")
+ >>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd " ef">
This function is useful when generating attribute values for HTML or any SGML
# server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://betty.userland.com")
- print server
+ print(server)
try:
- print server.examples.getStateName(41)
+ print(server.examples.getStateName(41))
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
transport. The following example, written by NoboNobo, shows how:
p = ProxiedTransport()
p.set_proxy('proxy-server:8080')
server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p)
- print server.currentTime.getCurrentTime()
+ print(server.currentTime.getCurrentTime())