Kaydet (Commit) 45e2fbc2 authored tarafından Guido van Rossum's avatar Guido van Rossum

Mass check-in after untabifying all files that need it.

üst 9ea70247
This diff is collapsed.
......@@ -41,47 +41,47 @@ class BastionClass:
"""
def __init__(self, get, name):
"""Constructor.
"""Constructor.
Arguments:
Arguments:
get - a function that gets the attribute value (by name)
name - a human-readable name for the original object
(suggestion: use repr(object))
get - a function that gets the attribute value (by name)
name - a human-readable name for the original object
(suggestion: use repr(object))
"""
self._get_ = get
self._name_ = name
"""
self._get_ = get
self._name_ = name
def __repr__(self):
"""Return a representation string.
"""Return a representation string.
This includes the name passed in to the constructor, so that
if you print the bastion during debugging, at least you have
some idea of what it is.
This includes the name passed in to the constructor, so that
if you print the bastion during debugging, at least you have
some idea of what it is.
"""
return "<Bastion for %s>" % self._name_
"""
return "<Bastion for %s>" % self._name_
def __getattr__(self, name):
"""Get an as-yet undefined attribute value.
"""Get an as-yet undefined attribute value.
This calls the get() function that was passed to the
constructor. The result is stored as an instance variable so
that the next time the same attribute is requested,
__getattr__() won't be invoked.
This calls the get() function that was passed to the
constructor. The result is stored as an instance variable so
that the next time the same attribute is requested,
__getattr__() won't be invoked.
If the get() function raises an exception, this is simply
passed on -- exceptions are not cached.
If the get() function raises an exception, this is simply
passed on -- exceptions are not cached.
"""
attribute = self._get_(name)
self.__dict__[name] = attribute
return attribute
"""
attribute = self._get_(name)
self.__dict__[name] = attribute
return attribute
def Bastion(object, filter = lambda name: name[:1] != '_',
name=None, bastionclass=BastionClass):
name=None, bastionclass=BastionClass):
"""Create a bastion for an object, using an optional filter.
See the Bastion module's documentation for background.
......@@ -109,33 +109,33 @@ def Bastion(object, filter = lambda name: name[:1] != '_',
# the user has full access to all instance variables!
def get1(name, object=object, filter=filter):
"""Internal function for Bastion(). See source comments."""
if filter(name):
attribute = getattr(object, name)
if type(attribute) == MethodType:
return attribute
raise AttributeError, name
"""Internal function for Bastion(). See source comments."""
if filter(name):
attribute = getattr(object, name)
if type(attribute) == MethodType:
return attribute
raise AttributeError, name
def get2(name, get1=get1):
"""Internal function for Bastion(). See source comments."""
return get1(name)
"""Internal function for Bastion(). See source comments."""
return get1(name)
if name is None:
name = `object`
name = `object`
return bastionclass(get2, name)
def _test():
"""Test the Bastion() function."""
class Original:
def __init__(self):
self.sum = 0
def add(self, n):
self._add(n)
def _add(self, n):
self.sum = self.sum + n
def total(self):
return self.sum
def __init__(self):
self.sum = 0
def add(self, n):
self._add(n)
def _add(self, n):
self.sum = self.sum + n
def total(self):
return self.sum
o = Original()
b = Bastion(o)
testcode = """if 1:
......@@ -143,23 +143,23 @@ def _test():
b.add(18)
print "b.total() =", b.total()
try:
print "b.sum =", b.sum,
print "b.sum =", b.sum,
except:
print "inaccessible"
print "inaccessible"
else:
print "accessible"
print "accessible"
try:
print "b._add =", b._add,
print "b._add =", b._add,
except:
print "inaccessible"
print "inaccessible"
else:
print "accessible"
print "accessible"
try:
print "b._get_.func_defaults =", b._get_.func_defaults,
print "b._get_.func_defaults =", b._get_.func_defaults,
except:
print "inaccessible"
print "inaccessible"
else:
print "accessible"
print "accessible"
\n"""
exec testcode
print '='*20, "Using rexec:", '='*20
......
......@@ -30,138 +30,138 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
def do_POST(self):
"""Serve a POST request.
"""Serve a POST request.
This is only implemented for CGI scripts.
This is only implemented for CGI scripts.
"""
"""
if self.is_cgi():
self.run_cgi()
else:
self.send_error(501, "Can only POST to CGI scripts")
if self.is_cgi():
self.run_cgi()
else:
self.send_error(501, "Can only POST to CGI scripts")
def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
def is_cgi(self):
"""test whether PATH corresponds to a CGI script.
"""test whether PATH corresponds to a CGI script.
Return a tuple (dir, rest) if PATH requires running a
CGI script, None if not. Note that rest begins with a
slash if it is not empty.
Return a tuple (dir, rest) if PATH requires running a
CGI script, None if not. Note that rest begins with a
slash if it is not empty.
The default implementation tests whether the path
begins with one of the strings in the list
self.cgi_directories (and the next character is a '/'
or the end of the string).
The default implementation tests whether the path
begins with one of the strings in the list
self.cgi_directories (and the next character is a '/'
or the end of the string).
"""
"""
path = self.path
path = self.path
for x in self.cgi_directories:
i = len(x)
if path[:i] == x and (not path[i:] or path[i] == '/'):
self.cgi_info = path[:i], path[i+1:]
return 1
return 0
for x in self.cgi_directories:
i = len(x)
if path[:i] == x and (not path[i:] or path[i] == '/'):
self.cgi_info = path[:i], path[i+1:]
return 1
return 0
cgi_directories = ['/cgi-bin', '/htbin']
def run_cgi(self):
"""Execute a CGI script."""
dir, rest = self.cgi_info
i = string.rfind(rest, '?')
if i >= 0:
rest, query = rest[:i], rest[i+1:]
else:
query = ''
i = string.find(rest, '/')
if i >= 0:
script, rest = rest[:i], rest[i:]
else:
script, rest = rest, ''
scriptname = dir + '/' + script
scriptfile = self.translate_path(scriptname)
if not os.path.exists(scriptfile):
self.send_error(404, "No such CGI script (%s)" % `scriptname`)
return
if not os.path.isfile(scriptfile):
self.send_error(403, "CGI script is not a plain file (%s)" %
`scriptname`)
return
if not executable(scriptfile):
self.send_error(403, "CGI script is not executable (%s)" %
`scriptname`)
return
nobody = nobody_uid()
self.send_response(200, "Script output follows")
self.wfile.flush() # Always flush before forking
pid = os.fork()
if pid != 0:
# Parent
pid, sts = os.waitpid(pid, 0)
if sts:
self.log_error("CGI script exit status x%x" % sts)
return
# Child
try:
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
# XXX Much of the following could be prepared ahead of time!
env = {}
env['SERVER_SOFTWARE'] = self.version_string()
env['SERVER_NAME'] = self.server.server_name
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['SERVER_PROTOCOL'] = self.protocol_version
env['SERVER_PORT'] = str(self.server.server_port)
env['REQUEST_METHOD'] = self.command
uqrest = urllib.unquote(rest)
env['PATH_INFO'] = uqrest
env['PATH_TRANSLATED'] = self.translate_path(uqrest)
env['SCRIPT_NAME'] = scriptname
if query:
env['QUERY_STRING'] = query
host = self.address_string()
if host != self.client_address[0]:
env['REMOTE_HOST'] = host
env['REMOTE_ADDR'] = self.client_address[0]
# AUTH_TYPE
# REMOTE_USER
# REMOTE_IDENT
env['CONTENT_TYPE'] = self.headers.type
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
accept = []
for line in self.headers.getallmatchingheaders('accept'):
if line[:1] in string.whitespace:
accept.append(string.strip(line))
else:
accept = accept + string.split(line[7:])
env['HTTP_ACCEPT'] = string.joinfields(accept, ',')
ua = self.headers.getheader('user-agent')
if ua:
env['HTTP_USER_AGENT'] = ua
# XXX Other HTTP_* headers
decoded_query = string.replace(query, '+', ' ')
try:
os.setuid(nobody)
except os.error:
pass
os.dup2(self.rfile.fileno(), 0)
os.dup2(self.wfile.fileno(), 1)
print scriptfile, script, decoded_query
os.execve(scriptfile,
[script, decoded_query],
env)
except:
self.server.handle_error(self.request, self.client_address)
os._exit(127)
"""Execute a CGI script."""
dir, rest = self.cgi_info
i = string.rfind(rest, '?')
if i >= 0:
rest, query = rest[:i], rest[i+1:]
else:
query = ''
i = string.find(rest, '/')
if i >= 0:
script, rest = rest[:i], rest[i:]
else:
script, rest = rest, ''
scriptname = dir + '/' + script
scriptfile = self.translate_path(scriptname)
if not os.path.exists(scriptfile):
self.send_error(404, "No such CGI script (%s)" % `scriptname`)
return
if not os.path.isfile(scriptfile):
self.send_error(403, "CGI script is not a plain file (%s)" %
`scriptname`)
return
if not executable(scriptfile):
self.send_error(403, "CGI script is not executable (%s)" %
`scriptname`)
return
nobody = nobody_uid()
self.send_response(200, "Script output follows")
self.wfile.flush() # Always flush before forking
pid = os.fork()
if pid != 0:
# Parent
pid, sts = os.waitpid(pid, 0)
if sts:
self.log_error("CGI script exit status x%x" % sts)
return
# Child
try:
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
# XXX Much of the following could be prepared ahead of time!
env = {}
env['SERVER_SOFTWARE'] = self.version_string()
env['SERVER_NAME'] = self.server.server_name
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['SERVER_PROTOCOL'] = self.protocol_version
env['SERVER_PORT'] = str(self.server.server_port)
env['REQUEST_METHOD'] = self.command
uqrest = urllib.unquote(rest)
env['PATH_INFO'] = uqrest
env['PATH_TRANSLATED'] = self.translate_path(uqrest)
env['SCRIPT_NAME'] = scriptname
if query:
env['QUERY_STRING'] = query
host = self.address_string()
if host != self.client_address[0]:
env['REMOTE_HOST'] = host
env['REMOTE_ADDR'] = self.client_address[0]
# AUTH_TYPE
# REMOTE_USER
# REMOTE_IDENT
env['CONTENT_TYPE'] = self.headers.type
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
accept = []
for line in self.headers.getallmatchingheaders('accept'):
if line[:1] in string.whitespace:
accept.append(string.strip(line))
else:
accept = accept + string.split(line[7:])
env['HTTP_ACCEPT'] = string.joinfields(accept, ',')
ua = self.headers.getheader('user-agent')
if ua:
env['HTTP_USER_AGENT'] = ua
# XXX Other HTTP_* headers
decoded_query = string.replace(query, '+', ' ')
try:
os.setuid(nobody)
except os.error:
pass
os.dup2(self.rfile.fileno(), 0)
os.dup2(self.wfile.fileno(), 1)
print scriptfile, script, decoded_query
os.execve(scriptfile,
[script, decoded_query],
env)
except:
self.server.handle_error(self.request, self.client_address)
os._exit(127)
nobody = None
......@@ -170,26 +170,26 @@ def nobody_uid():
"""Internal routine to get nobody's uid"""
global nobody
if nobody:
return nobody
return nobody
import pwd
try:
nobody = pwd.getpwnam('nobody')[2]
nobody = pwd.getpwnam('nobody')[2]
except pwd.error:
nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
return nobody
def executable(path):
"""Test for executable file."""
try:
st = os.stat(path)
st = os.stat(path)
except os.error:
return 0
return 0
return st[0] & 0111 != 0
def test(HandlerClass = CGIHTTPRequestHandler,
ServerClass = BaseHTTPServer.HTTPServer):
ServerClass = BaseHTTPServer.HTTPServer):
SimpleHTTPServer.test(HandlerClass, ServerClass)
......
This diff is collapsed.
......@@ -47,7 +47,7 @@ class MimeWriter:
w.startmultipartbody(subtype)
for each part:
subwriter = w.nextpart()
...use the subwriter's methods to create the subpart...
...use the subwriter's methods to create the subpart...
w.lastpart()
The subwriter is another MimeWriter instance, and should be
......@@ -82,46 +82,46 @@ class MimeWriter:
"""
def __init__(self, fp):
self._fp = fp
self._headers = []
self._fp = fp
self._headers = []
def addheader(self, key, value, prefix=0):
lines = string.splitfields(value, "\n")
while lines and not lines[-1]: del lines[-1]
while lines and not lines[0]: del lines[0]
for i in range(1, len(lines)):
lines[i] = " " + string.strip(lines[i])
value = string.joinfields(lines, "\n") + "\n"
line = key + ": " + value
if prefix:
self._headers.insert(0, line)
else:
self._headers.append(line)
lines = string.splitfields(value, "\n")
while lines and not lines[-1]: del lines[-1]
while lines and not lines[0]: del lines[0]
for i in range(1, len(lines)):
lines[i] = " " + string.strip(lines[i])
value = string.joinfields(lines, "\n") + "\n"
line = key + ": " + value
if prefix:
self._headers.insert(0, line)
else:
self._headers.append(line)
def flushheaders(self):
self._fp.writelines(self._headers)
self._headers = []
self._fp.writelines(self._headers)
self._headers = []
def startbody(self, ctype, plist=[], prefix=1):
for name, value in plist:
ctype = ctype + ';\n %s=\"%s\"' % (name, value)
self.addheader("Content-Type", ctype, prefix=prefix)
self.flushheaders()
self._fp.write("\n")
return self._fp
for name, value in plist:
ctype = ctype + ';\n %s=\"%s\"' % (name, value)
self.addheader("Content-Type", ctype, prefix=prefix)
self.flushheaders()
self._fp.write("\n")
return self._fp
def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
self._boundary = boundary or mimetools.choose_boundary()
return self.startbody("multipart/" + subtype,
[("boundary", self._boundary)] + plist,
prefix=prefix)
self._boundary = boundary or mimetools.choose_boundary()
return self.startbody("multipart/" + subtype,
[("boundary", self._boundary)] + plist,
prefix=prefix)
def nextpart(self):
self._fp.write("\n--" + self._boundary + "\n")
return self.__class__(self._fp)
self._fp.write("\n--" + self._boundary + "\n")
return self.__class__(self._fp)
def lastpart(self):
self._fp.write("\n--" + self._boundary + "--\n")
self._fp.write("\n--" + self._boundary + "--\n")
if __name__ == '__main__':
......
......@@ -4,102 +4,102 @@
# exceptions, but also when -X option is used.
try:
class Empty(Exception):
pass
pass
except TypeError:
# string based exceptions
Empty = 'Queue.Empty' # Exception raised by get_nowait()
Empty = 'Queue.Empty' # Exception raised by get_nowait()
class Queue:
def __init__(self, maxsize):
"""Initialize a queue object with a given maximum size.
"""Initialize a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
import thread
self._init(maxsize)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire_lock()
self.fsema = thread.allocate_lock()
If maxsize is <= 0, the queue size is infinite.
"""
import thread
self._init(maxsize)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire_lock()
self.fsema = thread.allocate_lock()
def qsize(self):
"""Returns the approximate size of the queue (not reliable!)."""
self.mutex.acquire_lock()
n = self._qsize()
self.mutex.release_lock()
return n
"""Returns the approximate size of the queue (not reliable!)."""
self.mutex.acquire_lock()
n = self._qsize()
self.mutex.release_lock()
return n
def empty(self):
"""Returns 1 if the queue is empty, 0 otherwise (not reliable!)."""
self.mutex.acquire_lock()
n = self._empty()
self.mutex.release_lock()
return n
"""Returns 1 if the queue is empty, 0 otherwise (not reliable!)."""
self.mutex.acquire_lock()
n = self._empty()
self.mutex.release_lock()
return n
def full(self):
"""Returns 1 if the queue is full, 0 otherwise (not reliable!)."""
self.mutex.acquire_lock()
n = self._full()
self.mutex.release_lock()
return n
"""Returns 1 if the queue is full, 0 otherwise (not reliable!)."""
self.mutex.acquire_lock()
n = self._full()
self.mutex.release_lock()
return n
def put(self, item):
"""Put an item into the queue."""
self.fsema.acquire_lock()
self.mutex.acquire_lock()
was_empty = self._empty()
self._put(item)
if was_empty:
self.esema.release_lock()
if not self._full():
self.fsema.release_lock()
self.mutex.release_lock()
"""Put an item into the queue."""
self.fsema.acquire_lock()
self.mutex.acquire_lock()
was_empty = self._empty()
self._put(item)
if was_empty:
self.esema.release_lock()
if not self._full():
self.fsema.release_lock()
self.mutex.release_lock()
def get(self):
"""Gets and returns an item from the queue.
This method blocks if necessary until an item is available.
"""
self.esema.acquire_lock()
self.mutex.acquire_lock()
was_full = self._full()
item = self._get()
if was_full:
self.fsema.release_lock()
if not self._empty():
self.esema.release_lock()
self.mutex.release_lock()
return item
"""Gets and returns an item from the queue.
This method blocks if necessary until an item is available.
"""
self.esema.acquire_lock()
self.mutex.acquire_lock()
was_full = self._full()
item = self._get()
if was_full:
self.fsema.release_lock()
if not self._empty():
self.esema.release_lock()
self.mutex.release_lock()
return item
# Get an item from the queue if one is immediately available,
# raise Empty if the queue is empty or temporarily unavailable
def get_nowait(self):
"""Gets and returns an item from the queue.
Only gets an item if one is immediately available, Otherwise
this raises the Empty exception if the queue is empty or
temporarily unavailable.
"""
locked = self.esema.acquire_lock(0)
self.mutex.acquire_lock()
if self._empty():
# The queue is empty -- we can't have esema
self.mutex.release_lock()
raise Empty
if not locked:
locked = self.esema.acquire_lock(0)
if not locked:
# Somebody else has esema
# but we have mutex --
# go out of their way
self.mutex.release_lock()
raise Empty
was_full = self._full()
item = self._get()
if was_full:
self.fsema.release_lock()
if not self._empty():
self.esema.release_lock()
self.mutex.release_lock()
return item
"""Gets and returns an item from the queue.
Only gets an item if one is immediately available, Otherwise
this raises the Empty exception if the queue is empty or
temporarily unavailable.
"""
locked = self.esema.acquire_lock(0)
self.mutex.acquire_lock()
if self._empty():
# The queue is empty -- we can't have esema
self.mutex.release_lock()
raise Empty
if not locked:
locked = self.esema.acquire_lock(0)
if not locked:
# Somebody else has esema
# but we have mutex --
# go out of their way
self.mutex.release_lock()
raise Empty
was_full = self._full()
item = self._get()
if was_full:
self.fsema.release_lock()
if not self._empty():
self.esema.release_lock()
self.mutex.release_lock()
return item
# XXX Need to define put_nowait() as well.
......@@ -110,26 +110,26 @@ class Queue:
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
self.maxsize = maxsize
self.queue = []
def _qsize(self):
return len(self.queue)
return len(self.queue)
# Check wheter the queue is empty
def _empty(self):
return not self.queue
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
self.queue.append(item)
# Get an item from the queue
def _get(self):
item = self.queue[0]
del self.queue[0]
return item
item = self.queue[0]
del self.queue[0]
return item
......@@ -36,119 +36,119 @@ class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
server_version = "SimpleHTTP/" + __version__
def do_GET(self):
"""Serve a GET request."""
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close()
"""Serve a GET request."""
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close()
def do_HEAD(self):
"""Serve a HEAD request."""
f = self.send_head()
if f:
f.close()
"""Serve a HEAD request."""
f = self.send_head()
if f:
f.close()
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
if os.path.isdir(path):
self.send_error(403, "Directory listing not supported")
return None
try:
f = open(path)
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", self.guess_type(path))
self.end_headers()
return f
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
if os.path.isdir(path):
self.send_error(403, "Directory listing not supported")
return None
try:
f = open(path)
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", self.guess_type(path))
self.end_headers()
return f
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
path = posixpath.normpath(path)
words = string.splitfields(path, '/')
words = filter(None, words)
path = os.getcwd()
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir): continue
path = os.path.join(path, word)
return path
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
path = posixpath.normpath(path)
words = string.splitfields(path, '/')
words = filter(None, words)
path = os.getcwd()
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir): continue
path = os.path.join(path, word)
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
"""
BLOCKSIZE = 8192
while 1:
data = source.read(BLOCKSIZE)
if not data: break
outputfile.write(data)
BLOCKSIZE = 8192
while 1:
data = source.read(BLOCKSIZE)
if not data: break
outputfile.write(data)
def guess_type(self, path):
"""Guess the type of a file.
"""Guess the type of a file.
Argument is a PATH (a filename).
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using text/plain
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
The default implementation looks the file's extension
up in the table self.extensions_map, using text/plain
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
"""
base, ext = posixpath.splitext(path)
if self.extensions_map.has_key(ext):
return self.extensions_map[ext]
ext = string.lower(ext)
if self.extensions_map.has_key(ext):
return self.extensions_map[ext]
else:
return self.extensions_map['']
base, ext = posixpath.splitext(path)
if self.extensions_map.has_key(ext):
return self.extensions_map[ext]
ext = string.lower(ext)
if self.extensions_map.has_key(ext):
return self.extensions_map[ext]
else:
return self.extensions_map['']
extensions_map = {
'': 'text/plain', # Default, *must* be present
'.html': 'text/html',
'.htm': 'text/html',
'.gif': 'image/gif',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
}
'': 'text/plain', # Default, *must* be present
'.html': 'text/html',
'.htm': 'text/html',
'.gif': 'image/gif',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
}
def test(HandlerClass = SimpleHTTPRequestHandler,
ServerClass = SocketServer.TCPServer):
ServerClass = SocketServer.TCPServer):
BaseHTTPServer.test(HandlerClass, ServerClass)
......
This diff is collapsed.
......@@ -4,30 +4,30 @@ class UserDict:
def __init__(self): self.data = {}
def __repr__(self): return repr(self.data)
def __cmp__(self, dict):
if type(dict) == type(self.data):
return cmp(self.data, dict)
else:
return cmp(self.data, dict.data)
if type(dict) == type(self.data):
return cmp(self.data, dict)
else:
return cmp(self.data, dict.data)
def __len__(self): return len(self.data)
def __getitem__(self, key): return self.data[key]
def __setitem__(self, key, item): self.data[key] = item
def __delitem__(self, key): del self.data[key]
def clear(self): return self.data.clear()
def copy(self):
import copy
return copy.copy(self)
import copy
return copy.copy(self)
def keys(self): return self.data.keys()
def items(self): return self.data.items()
def values(self): return self.data.values()
def has_key(self, key): return self.data.has_key(key)
def update(self, other):
if type(other) is type(self.data):
self.data.update(other)
else:
for k, v in other.items():
self.data[k] = v
if type(other) is type(self.data):
self.data.update(other)
else:
for k, v in other.items():
self.data[k] = v
def get(self, key, failobj=None):
if self.data.has_key(key):
return self.data[key]
else:
return failobj
if self.data.has_key(key):
return self.data[key]
else:
return failobj
This diff is collapsed.
......@@ -32,32 +32,32 @@ def compile_command(source, filename="<input>", symbol="single"):
code = code1 = code2 = None
try:
code = compile(source, filename, symbol)
code = compile(source, filename, symbol)
except SyntaxError, err:
pass
pass
try:
code1 = compile(source + "\n", filename, symbol)
code1 = compile(source + "\n", filename, symbol)
except SyntaxError, err1:
pass
pass
try:
code2 = compile(source + "\n\n", filename, symbol)
code2 = compile(source + "\n\n", filename, symbol)
except SyntaxError, err2:
pass
pass
if code:
return code
return code
try:
e1 = err1.__dict__
e1 = err1.__dict__
except AttributeError:
e1 = err1
e1 = err1
try:
e2 = err2.__dict__
e2 = err2.__dict__
except AttributeError:
e2 = err2
e2 = err2
if not code1 and e1 == e2:
raise SyntaxError, err1
raise SyntaxError, err1
def interact(banner=None, readfunc=raw_input, local=None):
......@@ -70,41 +70,41 @@ def interact(banner=None, readfunc=raw_input, local=None):
sys.ps1 = '>>> '
sys.ps2 = '... '
if banner:
print banner
print banner
else:
print "Python Interactive Console", sys.version
print sys.copyright
print "Python Interactive Console", sys.version
print sys.copyright
buf = []
while 1:
if buf: prompt = sys.ps2
else: prompt = sys.ps1
try: line = readfunc(prompt)
except KeyboardInterrupt:
print "\nKeyboardInterrupt"
buf = []
continue
except EOFError: break
buf.append(line)
try: x = compile_command(string.join(buf, "\n"))
except SyntaxError:
traceback.print_exc(0)
buf = []
continue
if x == None: continue
else:
try: exec x in local
except:
exc_type, exc_value, exc_traceback = \
sys.exc_type, sys.exc_value, \
sys.exc_traceback
l = len(traceback.extract_tb(sys.exc_traceback))
try: 1/0
except:
m = len(traceback.extract_tb(
sys.exc_traceback))
traceback.print_exception(exc_type,
exc_value, exc_traceback, l-m)
buf = []
if buf: prompt = sys.ps2
else: prompt = sys.ps1
try: line = readfunc(prompt)
except KeyboardInterrupt:
print "\nKeyboardInterrupt"
buf = []
continue
except EOFError: break
buf.append(line)
try: x = compile_command(string.join(buf, "\n"))
except SyntaxError:
traceback.print_exc(0)
buf = []
continue
if x == None: continue
else:
try: exec x in local
except:
exc_type, exc_value, exc_traceback = \
sys.exc_type, sys.exc_value, \
sys.exc_traceback
l = len(traceback.extract_tb(sys.exc_traceback))
try: 1/0
except:
m = len(traceback.extract_tb(
sys.exc_traceback))
traceback.print_exception(exc_type,
exc_value, exc_traceback, l-m)
buf = []
if __name__ == '__main__':
interact()
......@@ -72,11 +72,11 @@ def mk2arg(head, x):
#
def mkarg(x):
if '\'' not in x:
return ' \'' + x + '\''
return ' \'' + x + '\''
s = ' "'
for c in x:
if c in '\\$"`':
s = s + '\\'
s = s + c
if c in '\\$"`':
s = s + '\\'
s = s + c
s = s + '"'
return s
......@@ -29,36 +29,36 @@ def compile_dir(dir, maxlevels=10, ddir=None):
"""
print 'Listing', dir, '...'
try:
names = os.listdir(dir)
names = os.listdir(dir)
except os.error:
print "Can't list", dir
names = []
print "Can't list", dir
names = []
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, None, dfile)
except KeyboardInterrupt:
raise KeyboardInterrupt
except:
if type(sys.exc_type) == type(''):
exc_type_name = sys.exc_type
else: exc_type_name = sys.exc_type.__name__
print 'Sorry:', exc_type_name + ':',
print sys.exc_value
elif maxlevels > 0 and \
name != os.curdir and name != os.pardir and \
os.path.isdir(fullname) and \
not os.path.islink(fullname):
compile_dir(fullname, maxlevels - 1, dfile)
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, None, dfile)
except KeyboardInterrupt:
raise KeyboardInterrupt
except:
if type(sys.exc_type) == type(''):
exc_type_name = sys.exc_type
else: exc_type_name = sys.exc_type.__name__
print 'Sorry:', exc_type_name + ':',
print sys.exc_value
elif maxlevels > 0 and \
name != os.curdir and name != os.pardir and \
os.path.isdir(fullname) and \
not os.path.islink(fullname):
compile_dir(fullname, maxlevels - 1, dfile)
def compile_path(skip_curdir=1, maxlevels=0):
"""Byte-compile all module on sys.path.
......@@ -70,40 +70,40 @@ def compile_path(skip_curdir=1, maxlevels=0):
"""
for dir in sys.path:
if (not dir or dir == os.curdir) and skip_curdir:
print 'Skipping current directory'
else:
compile_dir(dir, maxlevels)
if (not dir or dir == os.curdir) and skip_curdir:
print 'Skipping current directory'
else:
compile_dir(dir, maxlevels)
def main():
"""Script main program."""
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'ld:')
opts, args = getopt.getopt(sys.argv[1:], 'ld:')
except getopt.error, msg:
print msg
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)
print msg
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 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)
if len(args) != 1:
print "-d destdir require exactly one directory argument"
sys.exit(2)
try:
if args:
for dir in args:
compile_dir(dir, maxlevels, ddir)
else:
compile_path()
if args:
for dir in args:
compile_dir(dir, maxlevels, ddir)
else:
compile_path()
except KeyboardInterrupt:
print "\n[interrupt]"
print "\n[interrupt]"
if __name__ == '__main__':
main()
......@@ -48,18 +48,18 @@ Exception(*)
class Exception:
def __init__(self, *args):
self.args = args
self.args = args
def __str__(self):
if not self.args:
return ''
elif len(self.args) == 1:
return str(self.args[0])
else:
return str(self.args)
elif len(self.args) == 1:
return str(self.args[0])
else:
return str(self.args)
def __getitem__(self, i):
return self.args[i]
return self.args[i]
class StandardError(Exception):
pass
......@@ -68,21 +68,21 @@ class SyntaxError(StandardError):
filename = lineno = offset = text = None
msg = ""
def __init__(self, *args):
self.args = args
if len(self.args) >= 1:
self.msg = self.args[0]
if len(self.args) == 2:
info = self.args[1]
try:
self.filename, self.lineno, self.offset, self.text = info
except:
pass
self.args = args
if len(self.args) >= 1:
self.msg = self.args[0]
if len(self.args) == 2:
info = self.args[1]
try:
self.filename, self.lineno, self.offset, self.text = info
except:
pass
def __str__(self):
return str(self.msg)
class IOError(StandardError):
def __init__(self, *args):
self.args = args
self.args = args
self.errno = None
self.strerror = None
if len(args) == 2:
......@@ -146,7 +146,7 @@ class MemoryError(StandardError):
class SystemExit(Exception):
def __init__(self, *args):
self.args = args
self.args = args
if len(args) == 0:
self.code = None
elif len(args) == 1:
......
......@@ -80,7 +80,7 @@ _state = None
def input(files=(), inplace=0, backup=""):
global _state
if _state and _state._file:
raise RuntimeError, "input() already active"
raise RuntimeError, "input() already active"
_state = FileInput(files, inplace, backup)
return _state
......@@ -89,151 +89,151 @@ def close():
state = _state
_state = None
if state:
state.close()
state.close()
def nextfile():
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError, "no active input()"
return _state.nextfile()
def filename():
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError, "no active input()"
return _state.filename()
def lineno():
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError, "no active input()"
return _state.lineno()
def filelineno():
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError, "no active input()"
return _state.filelineno()
def isfirstline():
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError, "no active input()"
return _state.isfirstline()
def isstdin():
if not _state:
raise RuntimeError, "no active input()"
raise RuntimeError, "no active input()"
return _state.isstdin()
class FileInput:
def __init__(self, files=(), inplace=0, backup=""):
if type(files) == type(''):
files = (files,)
else:
files = tuple(files)
if not files:
files = tuple(sys.argv[1:])
if not files:
files = ('-',)
self._files = files
self._inplace = inplace
self._backup = backup
self._savestdout = None
self._output = None
self._filename = None
self._lineno = 0
self._filelineno = 0
self._file = None
self._isstdin = 0
if type(files) == type(''):
files = (files,)
else:
files = tuple(files)
if not files:
files = tuple(sys.argv[1:])
if not files:
files = ('-',)
self._files = files
self._inplace = inplace
self._backup = backup
self._savestdout = None
self._output = None
self._filename = None
self._lineno = 0
self._filelineno = 0
self._file = None
self._isstdin = 0
def __del__(self):
self.close()
self.close()
def close(self):
self.nextfile()
self._files = ()
self.nextfile()
self._files = ()
def __getitem__(self, i):
if i != self._lineno:
raise RuntimeError, "accessing lines out of order"
line = self.readline()
if not line:
raise IndexError, "end of input reached"
return line
if i != self._lineno:
raise RuntimeError, "accessing lines out of order"
line = self.readline()
if not line:
raise IndexError, "end of input reached"
return line
def nextfile(self):
savestdout = self._savestdout
self._savestdout = 0
if savestdout:
sys.stdout = savestdout
savestdout = self._savestdout
self._savestdout = 0
if savestdout:
sys.stdout = savestdout
output = self._output
self._output = 0
if output:
output.close()
output = self._output
self._output = 0
if output:
output.close()
file = self._file
self._file = 0
if file and not self._isstdin:
file.close()
file = self._file
self._file = 0
if file and not self._isstdin:
file.close()
backupfilename = self._backupfilename
self._backupfilename = 0
if backupfilename and not self._backup:
try: os.unlink(backupfilename)
except: pass
backupfilename = self._backupfilename
self._backupfilename = 0
if backupfilename and not self._backup:
try: os.unlink(backupfilename)
except: pass
self._isstdin = 0
self._isstdin = 0
def readline(self):
if not self._file:
if not self._files:
return ""
self._filename = self._files[0]
self._files = self._files[1:]
self._filelineno = 0
self._file = None
self._isstdin = 0
self._backupfilename = 0
if self._filename == '-':
self._filename = '<stdin>'
self._file = sys.stdin
self._isstdin = 1
else:
if self._inplace:
self._backupfilename = (
self._filename + (self._backup or ".bak"))
try: os.unlink(self._backupfilename)
except os.error: pass
# The next three lines may raise IOError
os.rename(self._filename, self._backupfilename)
self._file = open(self._backupfilename, "r")
self._output = open(self._filename, "w")
self._savestdout = sys.stdout
sys.stdout = self._output
else:
# This may raise IOError
self._file = open(self._filename, "r")
line = self._file.readline()
if line:
self._lineno = self._lineno + 1
self._filelineno = self._filelineno + 1
return line
self.nextfile()
# Recursive call
return self.readline()
if not self._file:
if not self._files:
return ""
self._filename = self._files[0]
self._files = self._files[1:]
self._filelineno = 0
self._file = None
self._isstdin = 0
self._backupfilename = 0
if self._filename == '-':
self._filename = '<stdin>'
self._file = sys.stdin
self._isstdin = 1
else:
if self._inplace:
self._backupfilename = (
self._filename + (self._backup or ".bak"))
try: os.unlink(self._backupfilename)
except os.error: pass
# The next three lines may raise IOError
os.rename(self._filename, self._backupfilename)
self._file = open(self._backupfilename, "r")
self._output = open(self._filename, "w")
self._savestdout = sys.stdout
sys.stdout = self._output
else:
# This may raise IOError
self._file = open(self._filename, "r")
line = self._file.readline()
if line:
self._lineno = self._lineno + 1
self._filelineno = self._filelineno + 1
return line
self.nextfile()
# Recursive call
return self.readline()
def filename(self):
return self._filename
return self._filename
def lineno(self):
return self._lineno
return self._lineno
def filelineno(self):
return self._filelineno
return self._filelineno
def isfirstline(self):
return self._filelineno == 1
return self._filelineno == 1
def isstdin(self):
return self._isstdin
return self._isstdin
def _test():
import getopt
......@@ -241,13 +241,13 @@ def _test():
backup = 0
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
if o == '-i': inplace = 1
if o == '-b': backup = a
if o == '-i': inplace = 1
if o == '-b': backup = a
for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
isfirstline() and "*" or "", line)
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
isfirstline() and "*" or "", line)
print "%d: %s[%d]" % (lineno(), filename(), filelineno())
if __name__ == '__main__':
......
This diff is collapsed.
......@@ -21,11 +21,11 @@
# detects an error.
# It returns two values:
# (1) a list of pairs (option, option_argument) giving the options in
# the order in which they were specified. (I'd use a dictionary
# but applications may depend on option order or multiple
# occurrences.) Boolean options have '' as option_argument.
# (2) the list of remaining arguments (may be empty).
# (1) a list of pairs (option, option_argument) giving the options in
# the order in which they were specified. (I'd use a dictionary
# but applications may depend on option order or multiple
# occurrences.) Boolean options have '' as option_argument.
# (2) the list of remaining arguments (may be empty).
import string
......@@ -36,31 +36,31 @@ def getopt(args, shortopts, longopts = []):
longopts = longopts[:]
longopts.sort()
while args and args[0][:1] == '-' and args[0] != '-':
if args[0] == '--':
args = args[1:]
break
if args[0][:2] == '--':
list, args = do_longs(list, args[0][2:], longopts, args[1:])
else:
list, args = do_shorts(list, args[0][1:], shortopts, args[1:])
if args[0] == '--':
args = args[1:]
break
if args[0][:2] == '--':
list, args = do_longs(list, args[0][2:], longopts, args[1:])
else:
list, args = do_shorts(list, args[0][1:], shortopts, args[1:])
return list, args
def do_longs(list, opt, longopts, args):
try:
i = string.index(opt, '=')
opt, optarg = opt[:i], opt[i+1:]
i = string.index(opt, '=')
opt, optarg = opt[:i], opt[i+1:]
except ValueError:
optarg = None
optarg = None
has_arg, opt = long_has_args(opt, longopts)
if has_arg:
if optarg is None:
if not args:
raise error, 'option --%s requires argument' % opt
optarg, args = args[0], args[1:]
if optarg is None:
if not args:
raise error, 'option --%s requires argument' % opt
optarg, args = args[0], args[1:]
elif optarg:
raise error, 'option --%s must not have an argument' % opt
raise error, 'option --%s must not have an argument' % opt
list.append(('--' + opt, optarg or ''))
return list, args
......@@ -70,35 +70,35 @@ def do_longs(list, opt, longopts, args):
def long_has_args(opt, longopts):
optlen = len(opt)
for i in range(len(longopts)):
x, y = longopts[i][:optlen], longopts[i][optlen:]
if opt != x:
continue
if y != '' and y != '=' and i+1 < len(longopts):
if opt == longopts[i+1][:optlen]:
raise error, 'option --%s not a unique prefix' % opt
if longopts[i][-1:] in ('=', ):
return 1, longopts[i][:-1]
return 0, longopts[i]
x, y = longopts[i][:optlen], longopts[i][optlen:]
if opt != x:
continue
if y != '' and y != '=' and i+1 < len(longopts):
if opt == longopts[i+1][:optlen]:
raise error, 'option --%s not a unique prefix' % opt
if longopts[i][-1:] in ('=', ):
return 1, longopts[i][:-1]
return 0, longopts[i]
raise error, 'option --' + opt + ' not recognized'
def do_shorts(list, optstring, shortopts, args):
while optstring != '':
opt, optstring = optstring[0], optstring[1:]
if short_has_arg(opt, shortopts):
if optstring == '':
if not args:
raise error, 'option -%s requires argument' % opt
optstring, args = args[0], args[1:]
optarg, optstring = optstring, ''
else:
optarg = ''
list.append(('-' + opt, optarg))
opt, optstring = optstring[0], optstring[1:]
if short_has_arg(opt, shortopts):
if optstring == '':
if not args:
raise error, 'option -%s requires argument' % opt
optstring, args = args[0], args[1:]
optarg, optstring = optstring, ''
else:
optarg = ''
list.append(('-' + opt, optarg))
return list, args
def short_has_arg(opt, shortopts):
for i in range(len(shortopts)):
if opt == shortopts[i] != ':':
return shortopts[i+1:i+2] == ':'
if opt == shortopts[i] != ':':
return shortopts[i+1:i+2] == ':'
raise error, 'option -%s not recognized' % opt
if __name__ == '__main__':
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -63,10 +63,10 @@ def main():
while 1:
line = fp.readline()
if not line: break
if string.find(line, '{1, "') > -1:
match = strprog.search(line)
if match:
lines.append(" '" + match.group(1) + "',\n")
if string.find(line, '{1, "') > -1:
match = strprog.search(line)
if match:
lines.append(" '" + match.group(1) + "',\n")
fp.close()
lines.sort()
......
This diff is collapsed.
......@@ -11,21 +11,21 @@ def _group(s):
if not grouping:return s
result=""
while s and grouping:
# if grouping is -1, we are done
if grouping[0]==CHAR_MAX:
break
# 0: re-use last group ad infinitum
elif grouping[0]!=0:
#process last group
group=grouping[0]
grouping=grouping[1:]
if result:
result=s[-group:]+conv['thousands_sep']+result
else:
result=s[-group:]
s=s[:-group]
# if grouping is -1, we are done
if grouping[0]==CHAR_MAX:
break
# 0: re-use last group ad infinitum
elif grouping[0]!=0:
#process last group
group=grouping[0]
grouping=grouping[1:]
if result:
result=s[-group:]+conv['thousands_sep']+result
else:
result=s[-group:]
s=s[:-group]
if s and result:
result=s+conv['thousands_sep']+result
result=s+conv['thousands_sep']+result
return result
def format(f,val,grouping=0):
......@@ -35,13 +35,13 @@ def format(f,val,grouping=0):
result = f % val
fields = string.splitfields(result,".")
if grouping:
fields[0]=_group(fields[0])
fields[0]=_group(fields[0])
if len(fields)==2:
return fields[0]+localeconv()['decimal_point']+fields[1]
return fields[0]+localeconv()['decimal_point']+fields[1]
elif len(fields)==1:
return fields[0]
return fields[0]
else:
raise Error,"Too many decimal points in result string"
raise Error,"Too many decimal points in result string"
def str(val):
"""Convert float to integer, taking the locale into account."""
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -48,49 +48,49 @@ def guess_type(url):
"""
if not inited:
init()
init()
base, ext = posixpath.splitext(url)
while suffix_map.has_key(ext):
base, ext = posixpath.splitext(base + suffix_map[ext])
base, ext = posixpath.splitext(base + suffix_map[ext])
if encodings_map.has_key(ext):
encoding = encodings_map[ext]
base, ext = posixpath.splitext(base)
encoding = encodings_map[ext]
base, ext = posixpath.splitext(base)
else:
encoding = None
encoding = None
if types_map.has_key(ext):
return types_map[ext], encoding
return types_map[ext], encoding
elif types_map.has_key(string.lower(ext)):
return types_map[string.lower(ext)], encoding
return types_map[string.lower(ext)], encoding
else:
return None, encoding
return None, encoding
def init(files=None):
global inited
for file in files or knownfiles:
s = read_mime_types(file)
if s:
for key, value in s.items():
types_map[key] = value
s = read_mime_types(file)
if s:
for key, value in s.items():
types_map[key] = value
inited = 1
def read_mime_types(file):
try:
f = open(file)
f = open(file)
except IOError:
return None
return None
map = {}
while 1:
line = f.readline()
if not line: break
words = string.split(line)
for i in range(len(words)):
if words[i][0] == '#':
del words[i:]
break
if not words: continue
type, suffixes = words[0], words[1:]
for suff in suffixes:
map['.'+suff] = type
line = f.readline()
if not line: break
words = string.split(line)
for i in range(len(words)):
if words[i][0] == '#':
del words[i:]
break
if not words: continue
type, suffixes = words[0], words[1:]
for suff in suffixes:
map['.'+suff] = type
f.close()
return map
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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