Commit 548703a1 authored by Guido van Rossum's avatar Guido van Rossum

The usual.

parent 65e53990
# Routines to force "compilation" of all .py files in a directory
# tree or on sys.path. By default recursion is pruned at a depth of
# 10 and the current directory, if it occurs in sys.path, is skipped.
# When called as a script, compiles argument directories, or sys.path
# if no arguments.
# After a similar module by Sjoerd Mullender.
"""Module/script to "compile" all .py files to .pyc (or .pyo) file.
When called as a script with arguments, this compiles the directories
given as arguments recursively; the -l option prevents it from
recursing into directories.
Without arguments, if compiles all modules on sys.path, without
recursing into subdirectories. (Even though it should do so for
packages -- for now, you'll have to deal with packages separately.)
See module py_compile for details of the actual byte-compilation.
"""
import os
import sys
import py_compile
def compile_dir(dir, maxlevels = 10):
def compile_dir(dir, maxlevels=10, ddir=None):
"""Byte-compile all modules in the given directory tree.
Arguments (only dir is required):
dir: the directory to byte-compile
maxlevels: maximum recursion level (default 10)
ddir: if given, purported directory name (this is the
directory name that will show up in error messages)
"""
print 'Listing', dir, '...'
try:
names = os.listdir(dir)
......@@ -19,16 +36,18 @@ def compile_dir(dir, maxlevels = 10):
names.sort()
for name in names:
fullname = os.path.join(dir, name)
if ddir:
dfile = os.path.join(ddir, name)
else:
dfile = None
if os.path.isfile(fullname):
head, tail = name[:-3], name[-3:]
if tail == '.py':
print 'Compiling', fullname, '...'
try:
py_compile.compile(fullname)
py_compile.compile(fullname, None, dfile)
except KeyboardInterrupt:
del names[:]
print '\n[interrupt]'
break
raise KeyboardInterrupt
except:
if type(sys.exc_type) == type(''):
exc_type_name = sys.exc_type
......@@ -39,32 +58,52 @@ def compile_dir(dir, maxlevels = 10):
name != os.curdir and name != os.pardir and \
os.path.isdir(fullname) and \
not os.path.islink(fullname):
compile_dir(fullname, maxlevels - 1)
compile_dir(fullname, maxlevels - 1, dfile)
def compile_path(skip_curdir = 1):
def compile_path(skip_curdir=1, maxlevels=0):
"""Byte-compile all module on sys.path.
Arguments (all optional):
skip_curdir: if true, skip current directory (default true)
maxlevels: max recursion level (default 0)
"""
for dir in sys.path:
if (not dir or dir == os.curdir) and skip_curdir:
print 'Skipping current directory'
else:
compile_dir(dir, 0)
compile_dir(dir, maxlevels)
def main():
"""Script main program."""
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'l')
opts, args = getopt.getopt(sys.argv[1:], 'ld:')
except getopt.error, msg:
print msg
print "usage: compileall [-l] [directory ...]"
print "usage: compileall [-l] [-d destdir] [directory ...]"
print "-l: don't recurse down"
print "-d destdir: purported directory name for error messages"
print "if no arguments, -l sys.path is assumed"
sys.exit(2)
maxlevels = 10
ddir = None
for o, a in opts:
if o == '-l': maxlevels = 0
if o == '-d': ddir = a
if ddir:
if len(args) != 1:
print "-d destdir require exactly one directory argument"
sys.exit(2)
try:
if args:
for dir in sys.argv[1:]:
compile_dir(dir, maxlevels)
for dir in args:
compile_dir(dir, maxlevels, ddir)
else:
compile_path()
except KeyboardInterrupt:
print "\n[interrupt]"
if __name__ == '__main__':
main()
......@@ -164,13 +164,14 @@ class ConfigParser:
The section DEFAULT is special.
"""
try:
d = self.__sections[section].copy()
sectdict = self.__sections[section].copy()
except KeyError:
if section == DEFAULTSECT:
d = {}
sectdict = {}
else:
raise NoSectionError(section)
d.update(self.__defaults)
d = self.__defaults.copy()
d.update(sectdict)
option = string.lower(option)
try:
rawval = d[option]
......
......@@ -38,10 +38,10 @@ A_PLUS_SOUND = '<'
# Function mapping all file types to strings; unknown types become TYPE='x'
_names = dir()
_type_to_name_map = None
_type_to_name_map = {}
def type_to_name(gtype):
global _type_to_name_map
if not _type_to_name_map:
if _type_to_name_map=={}:
for name in _names:
if name[:2] == 'A_':
_type_to_name_map[eval(name)] = name[2:]
......@@ -75,6 +75,22 @@ def send_selector(selector, host, port = 0):
def send_query(selector, query, host, port = 0):
return send_selector(selector + '\t' + query, host, port)
# Takes a path as returned by urlparse and returns the appropriate selector
def path_to_selector(path):
if path=="/":
return "/"
else:
return path[2:] # Cuts initial slash and data type identifier
# Takes a path as returned by urlparse and maps it to a string
# See section 3.4 of RFC 1738 for details
def path_to_datatype_name(path):
if path=="/":
# No way to tell, although "INDEX" is likely
return "TYPE='unknown'"
else:
return type_to_name(path[1])
# The following functions interpret the data returned by the gopher
# server according to the expected type, e.g. textfile or directory
......@@ -103,7 +119,8 @@ def get_directory(f):
continue
if len(parts) > 4:
if parts[4:] != ['+']:
print '(Extra info from server:', parts[4:], ')'
print '(Extra info from server:',
print parts[4:], ')'
else:
parts.append('')
parts.insert(0, gtype)
......
......@@ -44,8 +44,17 @@ class MultiFile:
return self.lastpos
return self.fp.tell() - self.start
#
def seek(self, pos):
if not 0 <= pos <= self.tell() or \
def seek(self, pos, whence=0):
here = self.tell()
if whence:
if whence == 1:
pos = pos + here
elif whence == 2:
if self.level > 0:
pos = pos + self.lastpos
else:
raise Error, "can't use whence=2 yet"
if not 0 <= pos <= here or \
self.level > 0 and pos > self.lastpos:
raise Error, 'bad MultiFile.seek() call'
self.fp.seek(pos + self.start)
......
# Routine to "compile" a .py file to a .pyc file.
# This has intimate knowledge of how Python/import.c does it.
# By Sjoerd Mullender (I forced him to write it :-).
"""Routine to "compile" a .py file to a .pyc (or .pyo) file.
This module has intimate knowledge of the format of .pyc files.
"""
import imp
MAGIC = imp.get_magic()
def wr_long(f, x):
"Internal; write a 32-bit int to a file in little-endian order."
f.write(chr( x & 0xff))
f.write(chr((x >> 8) & 0xff))
f.write(chr((x >> 16) & 0xff))
f.write(chr((x >> 24) & 0xff))
def compile(file, cfile = None):
def compile(file, cfile=None, dfile=None):
"""Byte-compile one Python source file to Python bytecode.
Arguments:
file: source filename
cfile: target filename; defaults to source with 'c' or 'o' appended
('c' normally, 'o' in optimizing mode, giving .pyc or .pyo)
dfile: purported filename; defaults to source (this is the filename
that will show up in error messages)
Note that it isn't necessary to byte-compile Python modules for
execution efficiency -- Python itself byte-compiles a module when
it is loaded, and if it can, writes out the bytecode to the
corresponding .pyc (or .pyo) file.
However, if a Python installation is shared between users, it is a
good idea to byte-compile all modules upon installation, since
other users may not be able to write in the source directories,
and thus they won't be able to write the .pyc/.pyo file, and then
they would be byte-compiling every module each time it is loaded.
This can slow down program start-up considerably.
See compileall.py for a script/module that uses this module to
byte-compile all installed files (or all files in selected
directories).
"""
import os, marshal, __builtin__
f = open(file)
try:
......@@ -20,7 +49,9 @@ def compile(file, cfile = None):
timestamp = long(os.stat(file)[8])
codestring = f.read()
f.close()
codeobject = __builtin__.compile(codestring, file, 'exec')
if codestring and codestring[-1] != '\n':
codestring = codestring + '\n'
codeobject = __builtin__.compile(codestring, dfile or file, 'exec')
if not cfile:
cfile = file + (__debug__ and 'c' or 'o')
fc = open(cfile, 'wb')
......
......@@ -188,6 +188,7 @@ class Telnet:
"""
if IAC in buffer:
buffer = string.replace(buffer, IAC, IAC+IAC)
self.msg("send %s", `buffer`)
self.sock.send(buffer)
def read_until(self, match, timeout=None):
......@@ -365,6 +366,7 @@ class Telnet:
# The buffer size should be fairly small so as to avoid quadratic
# behavior in process_rawq() above
buf = self.sock.recv(50)
self.msg("recv %s", `buf`)
self.eof = (not buf)
self.rawq = self.rawq + buf
......
......@@ -5,7 +5,12 @@ import os
def findfile(file):
if os.path.isabs(file): return file
import sys
for dn in sys.path:
path = sys.path
try:
path = [os.path.dirname(__file__)] + path
except NameError:
pass
for dn in path:
fn = os.path.join(dn, file)
if os.path.exists(fn): return fn
return file
......
......@@ -161,6 +161,11 @@ if a <> [-2,-1,0,1,2]: raise TestFailed, 'list sort'
def revcmp(a, b): return cmp(b, a)
a.sort(revcmp)
if a <> [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
# The following dumps core in unpatched Python 1.5:
def myComparison(x,y):
return cmp(x%3, y%7)
z = range(12)
z.sort(myComparison)
print '6.6 Mappings == Dictionaries'
d = {}
......
'''Test module to thest the xmllib module.
Sjoerd Mullender
'''
from test_support import verbose
testdoc = """\
<?xml version="1.0" encoding="UTF-8" standalone='yes' ?>
<!-- comments aren't allowed before the <?xml?> tag,
but they are allowed before the <!DOCTYPE> tag -->
<!DOCTYPE greeting [
<!ELEMENT greeting (#PCDATA)>
]>
<greeting>Hello, world!</greeting>
"""
import xmllib
if verbose:
parser = xmllib.TestXMLParser()
else:
parser = xmllib.XMLParser()
for c in testdoc:
parser.feed(c)
parser.close()
......@@ -87,6 +87,8 @@ def format_exception(etype, value, tb, limit = None):
if tb:
list = ['Traceback (innermost last):\n']
list = list + format_tb(tb, limit)
else:
list = []
list = list + format_exception_only(etype, value)
return list
......@@ -186,9 +188,13 @@ def extract_stack(f=None, limit = None):
# with -O on).
# Coded by Marc-Andre Lemburg from the example of PyCode_Addr2Line()
# in compile.c.
# Revised version by Jim Hugunin to work with JPython too.
def tb_lineno(tb):
c = tb.tb_frame.f_code
if not hasattr(c, 'co_lnotab'):
return tb.tb_lineno
tab = c.co_lnotab
line = c.co_firstlineno
stopat = tb.tb_lasti
......
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