mirror of https://github.com/python/cpython.git
revert r69777 since all the experts agree that extra import lines distract from the code
This commit is contained in:
parent
5149742e8b
commit
a7b55a33f8
|
@ -267,8 +267,7 @@ sequence with comparable semantics, for example, yet many people write their own
|
||||||
:func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A
|
:func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A
|
||||||
classical use of :func:`reduce` is something like ::
|
classical use of :func:`reduce` is something like ::
|
||||||
|
|
||||||
import operator
|
import sys, operator
|
||||||
import sys
|
|
||||||
nums = map(float, sys.argv[1:])
|
nums = map(float, sys.argv[1:])
|
||||||
print reduce(operator.add, nums)/len(nums)
|
print reduce(operator.add, nums)/len(nums)
|
||||||
|
|
||||||
|
|
|
@ -99,8 +99,7 @@ simple CGI program::
|
||||||
# -*- coding: UTF-8 -*-
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
# enable debugging
|
# enable debugging
|
||||||
import cgitb
|
import cgitb; cgitb.enable()
|
||||||
cgitb.enable()
|
|
||||||
|
|
||||||
print "Content-Type: text/plain;charset=utf-8"
|
print "Content-Type: text/plain;charset=utf-8"
|
||||||
print
|
print
|
||||||
|
@ -280,9 +279,7 @@ following WSGI-application::
|
||||||
# -*- coding: UTF-8 -*-
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
from cgi import escape
|
from cgi import escape
|
||||||
import os
|
import sys, os
|
||||||
import sys
|
|
||||||
|
|
||||||
from flup.server.fcgi import WSGIServer
|
from flup.server.fcgi import WSGIServer
|
||||||
|
|
||||||
def app(environ, start_response):
|
def app(environ, start_response):
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
import datetime
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
import datetime, time
|
||||||
|
|
||||||
def adapt_datetime(ts):
|
def adapt_datetime(ts):
|
||||||
return time.mktime(ts.timetuple())
|
return time.mktime(ts.timetuple())
|
||||||
|
|
|
@ -246,8 +246,7 @@ asyncore Example basic HTTP client
|
||||||
Here is a very basic HTTP client that uses the :class:`dispatcher` class to
|
Here is a very basic HTTP client that uses the :class:`dispatcher` class to
|
||||||
implement its socket handling::
|
implement its socket handling::
|
||||||
|
|
||||||
import asyncore
|
import asyncore, socket
|
||||||
import socket
|
|
||||||
|
|
||||||
class http_client(asyncore.dispatcher):
|
class http_client(asyncore.dispatcher):
|
||||||
|
|
||||||
|
|
|
@ -67,20 +67,16 @@ Begin by writing ``import cgi``. Do not use ``from cgi import *`` --- the
|
||||||
module defines all sorts of names for its own use or for backward compatibility
|
module defines all sorts of names for its own use or for backward compatibility
|
||||||
that you don't want in your namespace.
|
that you don't want in your namespace.
|
||||||
|
|
||||||
When you write a new script, consider adding the following::
|
When you write a new script, consider adding the line::
|
||||||
|
|
||||||
import cgitb
|
import cgitb; cgitb.enable()
|
||||||
|
|
||||||
cgitb.enable()
|
|
||||||
|
|
||||||
This activates a special exception handler that will display detailed reports in
|
This activates a special exception handler that will display detailed reports in
|
||||||
the Web browser if any errors occur. If you'd rather not show the guts of your
|
the Web browser if any errors occur. If you'd rather not show the guts of your
|
||||||
program to users of your script, you can have the reports saved to files
|
program to users of your script, you can have the reports saved to files
|
||||||
instead, with something like this::
|
instead, with a line like this::
|
||||||
|
|
||||||
import cgitb
|
import cgitb; cgitb.enable(display=0, logdir="/tmp")
|
||||||
|
|
||||||
cgitb.enable(display=0, logdir="/tmp")
|
|
||||||
|
|
||||||
It's very helpful to use this feature during script development. The reports
|
It's very helpful to use this feature during script development. The reports
|
||||||
produced by :mod:`cgitb` provide information that can save you a lot of time in
|
produced by :mod:`cgitb` provide information that can save you a lot of time in
|
||||||
|
|
|
@ -231,8 +231,7 @@ RawConfigParser Objects
|
||||||
load the required file or files using :meth:`readfp` before calling :meth:`read`
|
load the required file or files using :meth:`readfp` before calling :meth:`read`
|
||||||
for any optional files::
|
for any optional files::
|
||||||
|
|
||||||
import ConfigParser
|
import ConfigParser, os
|
||||||
import os
|
|
||||||
|
|
||||||
config = ConfigParser.ConfigParser()
|
config = ConfigParser.ConfigParser()
|
||||||
config.readfp(open('defaults.cfg'))
|
config.readfp(open('defaults.cfg'))
|
||||||
|
|
|
@ -747,8 +747,7 @@ Examples
|
||||||
|
|
||||||
The first example shows the most common usage of :mod:`cookielib`::
|
The first example shows the most common usage of :mod:`cookielib`::
|
||||||
|
|
||||||
import cookielib
|
import cookielib, urllib2
|
||||||
import urllib2
|
|
||||||
cj = cookielib.CookieJar()
|
cj = cookielib.CookieJar()
|
||||||
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
|
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
|
||||||
r = opener.open("http://example.com/")
|
r = opener.open("http://example.com/")
|
||||||
|
@ -756,9 +755,7 @@ The first example shows the most common usage of :mod:`cookielib`::
|
||||||
This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
|
This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
|
||||||
cookies (assumes Unix/Netscape convention for location of the cookies file)::
|
cookies (assumes Unix/Netscape convention for location of the cookies file)::
|
||||||
|
|
||||||
import cookielib
|
import os, cookielib, urllib2
|
||||||
import os
|
|
||||||
import urllib2
|
|
||||||
cj = cookielib.MozillaCookieJar()
|
cj = cookielib.MozillaCookieJar()
|
||||||
cj.load(os.path.join(os.environ["HOME"], ".netscape/cookies.txt"))
|
cj.load(os.path.join(os.environ["HOME"], ".netscape/cookies.txt"))
|
||||||
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
|
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
|
||||||
|
|
|
@ -45,9 +45,7 @@ this module.
|
||||||
|
|
||||||
A simple example illustrating typical use::
|
A simple example illustrating typical use::
|
||||||
|
|
||||||
import crypt
|
import crypt, getpass, pwd
|
||||||
import getpass
|
|
||||||
import pwd
|
|
||||||
|
|
||||||
def login():
|
def login():
|
||||||
username = raw_input('Python login:')
|
username = raw_input('Python login:')
|
||||||
|
|
|
@ -460,8 +460,7 @@ Registering a new dialect::
|
||||||
|
|
||||||
A slightly more advanced use of the reader --- catching and reporting errors::
|
A slightly more advanced use of the reader --- catching and reporting errors::
|
||||||
|
|
||||||
import csv
|
import csv, sys
|
||||||
import sys
|
|
||||||
filename = "some.csv"
|
filename = "some.csv"
|
||||||
reader = csv.reader(open(filename, "rb"))
|
reader = csv.reader(open(filename, "rb"))
|
||||||
try:
|
try:
|
||||||
|
@ -507,9 +506,7 @@ For all other encodings the following :class:`UnicodeReader` and
|
||||||
parameter in their constructor and make sure that the data passes the real
|
parameter in their constructor and make sure that the data passes the real
|
||||||
reader or writer encoded as UTF-8::
|
reader or writer encoded as UTF-8::
|
||||||
|
|
||||||
import codecs
|
import csv, codecs, cStringIO
|
||||||
import cStringIO
|
|
||||||
import csv
|
|
||||||
|
|
||||||
class UTF8Recoder:
|
class UTF8Recoder:
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -708,11 +708,7 @@ It is also contained in the Python source distribution, as
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import difflib
|
import sys, os, time, difflib, optparse
|
||||||
import os
|
|
||||||
import optparse
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
# Configure the option parser
|
# Configure the option parser
|
||||||
|
|
|
@ -951,11 +951,9 @@ Python 2.4, :mod:`doctest`'s :class:`Tester` class is deprecated, and
|
||||||
test suites from modules and text files containing doctests. These test suites
|
test suites from modules and text files containing doctests. These test suites
|
||||||
can then be run using :mod:`unittest` test runners::
|
can then be run using :mod:`unittest` test runners::
|
||||||
|
|
||||||
import doctest
|
|
||||||
import unittest
|
import unittest
|
||||||
|
import doctest
|
||||||
import my_module_with_doctests
|
import my_module_with_doctests, and_another
|
||||||
import my_other_module_with_doctests
|
|
||||||
|
|
||||||
suite = unittest.TestSuite()
|
suite = unittest.TestSuite()
|
||||||
for mod in my_module_with_doctests, and_another:
|
for mod in my_module_with_doctests, and_another:
|
||||||
|
|
|
@ -133,9 +133,7 @@ The module defines the following functions:
|
||||||
|
|
||||||
Examples (all on a SVR4 compliant system)::
|
Examples (all on a SVR4 compliant system)::
|
||||||
|
|
||||||
import fcntl
|
import struct, fcntl, os
|
||||||
import os
|
|
||||||
import struct
|
|
||||||
|
|
||||||
f = open(...)
|
f = open(...)
|
||||||
rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)
|
rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)
|
||||||
|
|
|
@ -114,8 +114,7 @@ Using long option names is equally easy:
|
||||||
|
|
||||||
In a script, typical usage is something like this::
|
In a script, typical usage is something like this::
|
||||||
|
|
||||||
import getopt
|
import getopt, sys
|
||||||
import sys
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
try:
|
try:
|
||||||
|
|
|
@ -124,9 +124,7 @@ The following functions are non-standard or have special argument conventions:
|
||||||
|
|
||||||
Here is a tiny but complete example GL program in Python::
|
Here is a tiny but complete example GL program in Python::
|
||||||
|
|
||||||
import gl
|
import gl, GL, time
|
||||||
import GL
|
|
||||||
import time
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
gl.foreground()
|
gl.foreground()
|
||||||
|
|
|
@ -521,8 +521,7 @@ IMAP4 Example
|
||||||
Here is a minimal example (without error checking) that opens a mailbox and
|
Here is a minimal example (without error checking) that opens a mailbox and
|
||||||
retrieves and prints all messages::
|
retrieves and prints all messages::
|
||||||
|
|
||||||
import getpass
|
import getpass, imaplib
|
||||||
import imaplib
|
|
||||||
|
|
||||||
M = imaplib.IMAP4()
|
M = imaplib.IMAP4()
|
||||||
M.login(getpass.getuser(), getpass.getpass())
|
M.login(getpass.getuser(), getpass.getpass())
|
||||||
|
|
|
@ -112,9 +112,7 @@ This code is intended to be read, not executed. However, it does work
|
||||||
|
|
||||||
::
|
::
|
||||||
|
|
||||||
import __builtin__
|
import sys, imp, __builtin__
|
||||||
import imp
|
|
||||||
import sys
|
|
||||||
|
|
||||||
# Replacement for __import__()
|
# Replacement for __import__()
|
||||||
def import_hook(name, globals=None, locals=None, fromlist=None):
|
def import_hook(name, globals=None, locals=None, fromlist=None):
|
||||||
|
|
|
@ -1347,8 +1347,7 @@ Let's say you want to send logging events across a network, and handle them at
|
||||||
the receiving end. A simple way of doing this is attaching a
|
the receiving end. A simple way of doing this is attaching a
|
||||||
:class:`SocketHandler` instance to the root logger at the sending end::
|
:class:`SocketHandler` instance to the root logger at the sending end::
|
||||||
|
|
||||||
import logging
|
import logging, logging.handlers
|
||||||
import logging.handlers
|
|
||||||
|
|
||||||
rootLogger = logging.getLogger('')
|
rootLogger = logging.getLogger('')
|
||||||
rootLogger.setLevel(logging.DEBUG)
|
rootLogger.setLevel(logging.DEBUG)
|
||||||
|
@ -2601,9 +2600,7 @@ properly preceded with the binary-encoded length, as the new logging
|
||||||
configuration::
|
configuration::
|
||||||
|
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
import socket
|
import socket, sys, struct
|
||||||
import struct
|
|
||||||
import sys
|
|
||||||
|
|
||||||
data_to_send = open(sys.argv[1], "r").read()
|
data_to_send = open(sys.argv[1], "r").read()
|
||||||
|
|
||||||
|
|
|
@ -64,8 +64,7 @@ Example usage of :class:`ModuleFinder`
|
||||||
|
|
||||||
The script that is going to get analyzed later on (bacon.py)::
|
The script that is going to get analyzed later on (bacon.py)::
|
||||||
|
|
||||||
import itertools
|
import re, itertools
|
||||||
import re
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import baconhameggs
|
import baconhameggs
|
||||||
|
|
|
@ -708,8 +708,7 @@ The following example reads the resulting pickled data. When reading a
|
||||||
pickle-containing file, you should open the file in binary mode because you
|
pickle-containing file, you should open the file in binary mode because you
|
||||||
can't be sure if the ASCII or binary format was used. ::
|
can't be sure if the ASCII or binary format was used. ::
|
||||||
|
|
||||||
import pickle
|
import pprint, pickle
|
||||||
import pprint
|
|
||||||
|
|
||||||
pkl_file = open('data.pkl', 'rb')
|
pkl_file = open('data.pkl', 'rb')
|
||||||
|
|
||||||
|
|
|
@ -182,8 +182,7 @@ POP3 Example
|
||||||
Here is a minimal example (without error checking) that opens a mailbox and
|
Here is a minimal example (without error checking) that opens a mailbox and
|
||||||
retrieves and prints all messages::
|
retrieves and prints all messages::
|
||||||
|
|
||||||
import getpass
|
import getpass, poplib
|
||||||
import poplib
|
|
||||||
|
|
||||||
M = poplib.POP3('localhost')
|
M = poplib.POP3('localhost')
|
||||||
M.user(getpass.getuser())
|
M.user(getpass.getuser())
|
||||||
|
|
|
@ -228,8 +228,7 @@ serial device that may not be turned on, which would normally cause the
|
||||||
before opening the file; if the operation takes too long, the alarm signal will
|
before opening the file; if the operation takes too long, the alarm signal will
|
||||||
be sent, and the handler raises an exception. ::
|
be sent, and the handler raises an exception. ::
|
||||||
|
|
||||||
import os
|
import signal, os
|
||||||
import signal
|
|
||||||
|
|
||||||
def handler(signum, frame):
|
def handler(signum, frame):
|
||||||
print 'Signal handler called with signal', signum
|
print 'Signal handler called with signal', signum
|
||||||
|
|
|
@ -423,8 +423,7 @@ Connection Objects
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
# Convert file existing_db.db to SQL dump file dump.sql
|
# Convert file existing_db.db to SQL dump file dump.sql
|
||||||
import os
|
import sqlite3, os
|
||||||
import sqlite3
|
|
||||||
|
|
||||||
con = sqlite3.connect('existing_db.db')
|
con = sqlite3.connect('existing_db.db')
|
||||||
with open('dump.sql', 'w') as f:
|
with open('dump.sql', 'w') as f:
|
||||||
|
|
|
@ -481,9 +481,7 @@ Client-side operation
|
||||||
This example connects to an SSL server, prints the server's address and certificate,
|
This example connects to an SSL server, prints the server's address and certificate,
|
||||||
sends some bytes, and reads part of the response::
|
sends some bytes, and reads part of the response::
|
||||||
|
|
||||||
import pprint
|
import socket, ssl, pprint
|
||||||
import socket
|
|
||||||
import ssl
|
|
||||||
|
|
||||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
|
||||||
|
@ -537,8 +535,7 @@ For server operation, typically you'd need to have a server certificate, and pri
|
||||||
You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
|
You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
|
||||||
to connect::
|
to connect::
|
||||||
|
|
||||||
import socket
|
import socket, ssl
|
||||||
import ssl
|
|
||||||
|
|
||||||
bindsocket = socket.socket()
|
bindsocket = socket.socket()
|
||||||
bindsocket.bind(('myaddr.mydomain.com', 10023))
|
bindsocket.bind(('myaddr.mydomain.com', 10023))
|
||||||
|
|
|
@ -139,8 +139,7 @@ on the implementation of the underlying system call.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
import os
|
import os, sys
|
||||||
import sys
|
|
||||||
from stat import *
|
from stat import *
|
||||||
|
|
||||||
def walktree(top, callback):
|
def walktree(top, callback):
|
||||||
|
|
|
@ -135,13 +135,11 @@ methods (except ``control`` objects which only provide :meth:`getinfo`,
|
||||||
The audio device supports asynchronous notification of various events, through
|
The audio device supports asynchronous notification of various events, through
|
||||||
the SIGPOLL signal. Here's an example of how you might enable this in Python::
|
the SIGPOLL signal. Here's an example of how you might enable this in Python::
|
||||||
|
|
||||||
import fcntl
|
|
||||||
import signal
|
|
||||||
import STROPTS
|
|
||||||
|
|
||||||
def handle_sigpoll(signum, frame):
|
def handle_sigpoll(signum, frame):
|
||||||
print 'I got a SIGPOLL update'
|
print 'I got a SIGPOLL update'
|
||||||
|
|
||||||
|
import fcntl, signal, STROPTS
|
||||||
|
|
||||||
signal.signal(signal.SIGPOLL, handle_sigpoll)
|
signal.signal(signal.SIGPOLL, handle_sigpoll)
|
||||||
fcntl.ioctl(audio_obj.fileno(), STROPTS.I_SETSIG, STROPTS.S_MSG)
|
fcntl.ioctl(audio_obj.fileno(), STROPTS.I_SETSIG, STROPTS.S_MSG)
|
||||||
|
|
||||||
|
|
|
@ -91,8 +91,7 @@ technique using a separate :func:`tcgetattr` call and a :keyword:`try` ...
|
||||||
exactly no matter what happens::
|
exactly no matter what happens::
|
||||||
|
|
||||||
def getpass(prompt = "Password: "):
|
def getpass(prompt = "Password: "):
|
||||||
import sys
|
import termios, sys
|
||||||
import termios
|
|
||||||
fd = sys.stdin.fileno()
|
fd = sys.stdin.fileno()
|
||||||
old = termios.tcgetattr(fd)
|
old = termios.tcgetattr(fd)
|
||||||
new = termios.tcgetattr(fd)
|
new = termios.tcgetattr(fd)
|
||||||
|
|
|
@ -145,8 +145,7 @@ less useful than) the standard Python interactive interpreter loop. For a more
|
||||||
complete implementation of the interpreter loop, refer to the :mod:`code`
|
complete implementation of the interpreter loop, refer to the :mod:`code`
|
||||||
module. ::
|
module. ::
|
||||||
|
|
||||||
import sys
|
import sys, traceback
|
||||||
import traceback
|
|
||||||
|
|
||||||
def run_user_code(envdir):
|
def run_user_code(envdir):
|
||||||
source = raw_input(">>> ")
|
source = raw_input(">>> ")
|
||||||
|
@ -166,8 +165,7 @@ module. ::
|
||||||
The following example demonstrates the different ways to print and format the
|
The following example demonstrates the different ways to print and format the
|
||||||
exception and traceback::
|
exception and traceback::
|
||||||
|
|
||||||
import sys
|
import sys, traceback
|
||||||
import traceback
|
|
||||||
|
|
||||||
def lumberjack():
|
def lumberjack():
|
||||||
bright_side_of_death()
|
bright_side_of_death()
|
||||||
|
|
|
@ -551,8 +551,7 @@ transport. The following example shows how:
|
||||||
|
|
||||||
::
|
::
|
||||||
|
|
||||||
import httplib
|
import xmlrpclib, httplib
|
||||||
import xmlrpclib
|
|
||||||
|
|
||||||
class ProxiedTransport(xmlrpclib.Transport):
|
class ProxiedTransport(xmlrpclib.Transport):
|
||||||
def set_proxy(self, proxy):
|
def set_proxy(self, proxy):
|
||||||
|
|
|
@ -99,8 +99,7 @@ Automatic completion of variable and module names is optionally available. To
|
||||||
enable it in the interpreter's interactive mode, add the following to your
|
enable it in the interpreter's interactive mode, add the following to your
|
||||||
startup file: [#]_ ::
|
startup file: [#]_ ::
|
||||||
|
|
||||||
import readline
|
import rlcompleter, readline
|
||||||
import rlcompleter
|
|
||||||
readline.parse_and_bind('tab: complete')
|
readline.parse_and_bind('tab: complete')
|
||||||
|
|
||||||
This binds the :kbd:`Tab` key to the completion function, so hitting the
|
This binds the :kbd:`Tab` key to the completion function, so hitting the
|
||||||
|
|
|
@ -170,8 +170,7 @@ case is running I/O in parallel with computations in another thread.
|
||||||
The following code shows how the high level :mod:`threading` module can run
|
The following code shows how the high level :mod:`threading` module can run
|
||||||
tasks in background while the main program continues to run::
|
tasks in background while the main program continues to run::
|
||||||
|
|
||||||
import threading
|
import threading, zipfile
|
||||||
import zipfile
|
|
||||||
|
|
||||||
class AsyncZip(threading.Thread):
|
class AsyncZip(threading.Thread):
|
||||||
def __init__(self, infile, outfile):
|
def __init__(self, infile, outfile):
|
||||||
|
|
|
@ -473,8 +473,7 @@ statement both starts a database transaction and acquires a thread lock::
|
||||||
Finally, the :func:`closing(object)` function returns *object* so that it can be
|
Finally, the :func:`closing(object)` function returns *object* so that it can be
|
||||||
bound to a variable, and calls ``object.close`` at the end of the block. ::
|
bound to a variable, and calls ``object.close`` at the end of the block. ::
|
||||||
|
|
||||||
import sys
|
import urllib, sys
|
||||||
import urllib
|
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
|
|
||||||
with closing(urllib.urlopen('http://www.yahoo.com')) as f:
|
with closing(urllib.urlopen('http://www.yahoo.com')) as f:
|
||||||
|
|
Loading…
Reference in New Issue