['string.' + method for method in list_public_methods(self.string)]
def pow(self, x, y): return pow(x, y)
def add(self, x, y) : return x + y
-
+
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_introspection_functions()
server.register_instance(MyFuncs())
Returns a copy of a list without duplicates. Every list
item must be hashable and the order of the items in the
resulting list is not defined.
- """
+ """
u = {}
for x in lst:
u[x] = 1
and then to dispatch them. There should never be any
reason to instantiate this class directly.
"""
-
+
def __init__(self):
self.funcs = {}
self.instance = None
see http://xmlrpc.usefulinc.com/doc/reserved.html
"""
-
+
self.funcs.update({'system.listMethods' : self.system_listMethods,
'system.methodSignature' : self.system_methodSignature,
'system.methodHelp' : self.system_methodHelp})
namespace.
see http://www.xmlrpc.com/discuss/msgReader$1208"""
-
+
self.funcs.update({'system.multicall' : self.system_multicall})
-
+
def _marshaled_dispatch(self, data, dispatch_method = None):
"""Dispatches an XML-RPC method from marshalled (XML) data.
-
+
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
- function can be provided as an argument (see comment in
+ function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the prefered means
of changing method dispatch behavior.
"""
-
+
params, method = xmlrpclib.loads(data)
# generate response
try:
if dispatch_method is not None:
response = dispatch_method(method, params)
- else:
+ else:
response = self._dispatch(method, params)
# wrap response in a singleton tuple
response = (response,)
"""system.listMethods() => ['add', 'subtract', 'multiple']
Returns a list of the methods supported by the server."""
-
+
methods = self.funcs.keys()
if self.instance is not None:
# Instance can implement _listMethod to return a list of
)
methods.sort()
return methods
-
+
def system_methodSignature(self, method_name):
"""system.methodSignature('add') => [double, int, int]
This server does NOT support system.methodSignature."""
# See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html
-
+
return 'signatures not supported'
def system_methodHelp(self, method_name):
"""system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method."""
-
+
method = None
if self.funcs.has_key(method_name):
method = self.funcs[method_name]
Allows the caller to package multiple XML-RPC calls into a single
request.
- See http://www.xmlrpc.com/discuss/msgReader$1208
+ See http://www.xmlrpc.com/discuss/msgReader$1208
"""
-
+
results = []
for call in call_list:
method_name = call['methodName']
'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)}
)
return results
-
+
def _dispatch(self, method, params):
"""Dispatches the XML-RPC method.
return func(*params)
else:
raise Exception('method "%s" is not supported' % method)
-
+
class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Simple XML-RPC request handler class.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
"""
-
+
try:
# get arguments
data = self.rfile.read(int(self.headers["content-length"]))
# shut down the connection
self.wfile.flush()
self.connection.shutdown(1)
-
+
def log_request(self, code='-', size='-'):
"""Selectively log an accepted request."""
if self.server.logRequests:
BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)
-class SimpleXMLRPCServer(SocketServer.TCPServer,
+class SimpleXMLRPCServer(SocketServer.TCPServer,
SimpleXMLRPCDispatcher):
"""Simple XML-RPC server.
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
logRequests=1):
self.logRequests = logRequests
-
+
SimpleXMLRPCDispatcher.__init__(self)
SocketServer.TCPServer.__init__(self, addr, requestHandler)
-
+
class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
"""Simple handler for XML-RPC data passed through CGI."""
-
+
def __init__(self):
SimpleXMLRPCDispatcher.__init__(self)
def handle_xmlrpc(self, request_text):
"""Handle a single XML-RPC request"""
-
+
response = self._marshaled_dispatch(request_text)
-
+
print 'Content-Type: text/xml'
print 'Content-Length: %d' % len(response)
print
code = 400
message, explain = \
BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
-
+
response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % \
{
- 'code' : code,
- 'message' : message,
+ 'code' : code,
+ 'message' : message,
'explain' : explain
}
print 'Status: %d %s' % (code, message)
print 'Content-Length: %d' % len(response)
print
print response
-
+
def handle_request(self, request_text = None):
"""Handle a single XML-RPC request passed through a CGI post method.
-
+
If no XML data is given then it is read from stdin. The resulting
XML-RPC response is printed to stdout along with the correct HTTP
headers.
"""
-
+
if request_text is None and \
os.environ.get('REQUEST_METHOD', None) == 'GET':
self.handle_get()
else:
# POST data is normally available through stdin
if request_text is None:
- request_text = sys.stdin.read()
+ request_text = sys.stdin.read()
self.handle_xmlrpc(request_text)
-
+
if __name__ == '__main__':
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(pow)
#populous then just inline calculations. Also might be able to use
#``datetime`` and the methods it provides.
if julian == -1:
- julian = julianday(year, month, day)
+ julian = julianday(year, month, day)
else: # Assuming that if they bothered to include Julian day it will
#be accurate
- year, month, day = gregorian(julian, year)
+ year, month, day = gregorian(julian, year)
if weekday == -1:
- weekday = dayofweek(year, month, day)
+ weekday = dayofweek(year, month, day)
return time.struct_time((year, month, day,
hour, minute, second,
weekday, julian, tz))
not need to be rewritten for when the thread module is not present.
Suggested usage is::
-
+
try:
import thread
except ImportError:
class LockType(object):
"""Class implementing dummy implementation of thread.LockType.
-
+
Compatibility is maintained by maintaining self.locked_status
which is a boolean that stores the state of the lock. Pickling of
the lock, though, should not be done since if the thread module is
def __init__(self):
self.locked_status = False
-
+
def acquire(self, waitflag=None):
"""Dummy implementation of acquire().
"""
if waitflag is None:
self.locked_status = True
- return None
+ return None
elif not waitflag:
if not self.locked_status:
self.locked_status = True
return False
else:
self.locked_status = True
- return True
+ return True
def release(self):
"""Release the dummy lock."""
def basename(s): return split(s)[1]
def ismount(s):
- if not isabs(s):
- return False
- components = split(s)
- return len(components) == 2 and components[1] == ''
+ if not isabs(s):
+ return False
+ components = split(s)
+ return len(components) == 2 and components[1] == ''
def isdir(s):
"""Return true if the pathname refers to an existing directory."""
if isinstance(consts[i], type(co)):
consts[i] = self.replace_paths_in_code(consts[i])
- return new.code(co.co_argcount, co.co_nlocals, co.co_stacksize,
- co.co_flags, co.co_code, tuple(consts), co.co_names,
- co.co_varnames, new_filename, co.co_name,
+ return new.code(co.co_argcount, co.co_nlocals, co.co_stacksize,
+ co.co_flags, co.co_code, tuple(consts), co.co_names,
+ co.co_varnames, new_filename, co.co_name,
co.co_firstlineno, co.co_lnotab,
co.co_freevars, co.co_cellvars)
environ = _Environ(environ)
def getenv(key, default=None):
- """Get an environment variable, return None if it doesn't exist.
- The optional second argument can specify an alternate default."""
- return environ.get(key, default)
+ """Get an environment variable, return None if it doesn't exist.
+ The optional second argument can specify an alternate default."""
+ return environ.get(key, default)
__all__.append("getenv")
def _exists(name):
markmsg = None
if markstack and markobject in opcode.stack_before:
- assert markobject not in opcode.stack_after
- markpos = markstack.pop()
- if markpos is not None:
- markmsg = "(MARK at %d)" % markpos
+ assert markobject not in opcode.stack_after
+ markpos = markstack.pop()
+ if markpos is not None:
+ markmsg = "(MARK at %d)" % markpos
if arg is not None or markmsg:
# make a mild effort to align arguments
except ImportError:
return result
try:
- ioctl(result, I_PUSH, "ptem")
- ioctl(result, I_PUSH, "ldterm")
+ ioctl(result, I_PUSH, "ptem")
+ ioctl(result, I_PUSH, "ldterm")
except IOError:
pass
return result
raise PyCompileError(exc_type,exc_value,file[,msg])
where
-
+
exc_type: exception type to be used in error message
type name can be accesses as class variable
'exc_type_name'
-
+
exc_value: exception value to be used in error message
can be accesses as class variable 'exc_value'
-
+
file: name of file being compiled to be used in error message
can be accesses as class variable 'file'
-
+
msg: string message to be written as error message
If no value is given, a default exception message will be given,
consistent with 'standard' py_compile output.
message (or default) can be accesses as class variable 'msg'
-
+
"""
-
+
def __init__(self, exc_type, exc_value, file, msg=''):
exc_type_name = exc_type.__name__
if exc_type is SyntaxError:
errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
else:
errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
-
+
Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
self.exc_type_name = exc_type_name
and the function will return to the caller. If an
exception occurs and this flag is set to True, a
PyCompileError exception will be raised.
-
+
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
compile(filename, doraise=True)
except PyCompileError,err:
sys.stderr.write(err.msg)
-
+
if __name__ == "__main__":
main()
if self.posix:
prefix = tarinfo.name[:LENGTH_PREFIX + 1]
while prefix and prefix[-1] != "/":
- prefix = prefix[:-1]
+ prefix = prefix[:-1]
name = tarinfo.name[len(prefix):]
prefix = prefix[:-1]
return [p]
else:
assert False, "Internal error: Path not found in std_dirs or paths"
-
+
def module_enabled(extlist, modname):
"""Returns whether the module 'modname' is present in the list
of extensions 'extlist'."""
line = line.split()
remove_modules.append( line[0] )
input.close()
-
+
for ext in self.extensions[:]:
if ext.name in remove_modules:
self.extensions.remove(ext)
exts.append( Extension('datetime', ['datetimemodule.c'],
libraries=math_libs) )
# random number generator implemented in C
- exts.append( Extension("_random", ["_randommodule.c"]) )
+ exts.append( Extension("_random", ["_randommodule.c"]) )
# operator.add() and similar goodies
exts.append( Extension('operator', ['operator.c']) )
# Python C API test module
exts.append( Extension('fcntl', ['fcntlmodule.c']) )
if platform not in ['mac']:
# pwd(3)
- exts.append( Extension('pwd', ['pwdmodule.c']) )
- # grp(3)
- exts.append( Extension('grp', ['grpmodule.c']) )
+ exts.append( Extension('pwd', ['pwdmodule.c']) )
+ # grp(3)
+ exts.append( Extension('grp', ['grpmodule.c']) )
# select(2); not on ancient System V
exts.append( Extension('select', ['selectmodule.c']) )
# enigma-inspired encryption
exts.append( Extension('rotor', ['rotormodule.c']) )
if platform not in ['mac']:
- # syslog daemon interface
- exts.append( Extension('syslog', ['syslogmodule.c']) )
+ # syslog daemon interface
+ exts.append( Extension('syslog', ['syslogmodule.c']) )
# George Neville-Neil's timing module:
exts.append( Extension('timing', ['timingmodule.c']) )
libraries=readline_libs) )
if platform not in ['mac']:
# crypt module.
-
- if self.compiler.find_library_file(lib_dirs, 'crypt'):
- libs = ['crypt']
- else:
- libs = []
- exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
+
+ if self.compiler.find_library_file(lib_dirs, 'crypt'):
+ libs = ['crypt']
+ else:
+ libs = []
+ exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
# socket(2)
exts.append( Extension('_socket', ['socketmodule.c'],
db_search_order = db_try_this.keys()
db_search_order.sort()
db_search_order.reverse()
-
+
class found(Exception): pass
try:
# See whether there is a Sleepycat header in the standard
# Steen Lumholt's termios module
exts.append( Extension('termios', ['termios.c']) )
# Jeremy Hylton's rlimit interface
- if platform not in ['atheos']:
+ if platform not in ['atheos']:
exts.append( Extension('resource', ['resource.c']) )
# Sun yellow pages. Some systems have the functions in libc.
iconv_libraries = ['iconv']
else:
iconv_libraries = [] # in libc
-
+
exts.append( Extension('_iconv_codec',
['_iconv_codec.c'],
include_dirs = iconv_incs,
('XML_CONTEXT_BYTES','1024'),
],
include_dirs = [expatinc]
- ))
+ ))
# Dynamic loading module
if sys.maxint == 0x7fffffff:
# should put a symlink to your Waste installation in the
# same folder as your python source tree. Or modify the
# next few lines:-)
- waste_incs = find_file("WASTE.h", [],
+ waste_incs = find_file("WASTE.h", [],
['../'*n + 'waste/C_C++ Headers' for n in (0,1,2,3,4)])
waste_libs = find_library_file(self.compiler, "WASTE", [],
["../"*n + "waste/Static Libraries" for n in (0,1,2,3,4)])
(srcdir,) = sysconfig.get_config_vars('srcdir')
exts.append( Extension('waste',
['waste/wastemodule.c'] + [
- os.path.join(srcdir, d) for d in
+ os.path.join(srcdir, d) for d in
'Mac/Wastemods/WEObjectHandlers.c',
'Mac/Wastemods/WETabHooks.c',
'Mac/Wastemods/WETabs.c'
# different the UNIX search logic is not sharable.
from os.path import join, exists
framework_dirs = [
- '/System/Library/Frameworks/',
- '/Library/Frameworks',
+ '/System/Library/Frameworks/',
+ '/Library/Frameworks',
join(os.getenv('HOME'), '/Library/Frameworks')
]
# bundles.
# XXX distutils should support -F!
for F in framework_dirs:
- # both Tcl.framework and Tk.framework should be present
+ # both Tcl.framework and Tk.framework should be present
for fw in 'Tcl', 'Tk':
- if not exists(join(F, fw + '.framework')):
+ if not exists(join(F, fw + '.framework')):
break
else:
# ok, F is now directory with both frameworks. Continure
# Tk and Tcl frameworks not found. Normal "unix" tkinter search
# will now resume.
return 0
-
+
# For 8.4a2, we must add -I options that point inside the Tcl and Tk
# frameworks. In later release we should hopefully be able to pass
- # the -F option to gcc, which specifies a framework lookup path.
+ # the -F option to gcc, which specifies a framework lookup path.
#
include_dirs = [
- join(F, fw + '.framework', H)
+ join(F, fw + '.framework', H)
for fw in 'Tcl', 'Tk'
for H in 'Headers', 'Versions/Current/PrivateHeaders'
]
- # For 8.4a2, the X11 headers are not included. Rather than include a
+ # For 8.4a2, the X11 headers are not included. Rather than include a
# complicated search, this is a hard-coded path. It could bail out
# if X11 libs are not found...
include_dirs.append('/usr/X11R6/include')
self.extensions.append(ext)
return 1
-
+
def detect_tkinter(self, inc_dirs, lib_dirs):
# The _tkinter module.
platform = self.get_platform()
if platform == 'darwin' and \
self.detect_tkinter_darwin(inc_dirs, lib_dirs):
- return
+ return
# Set platform specific library prefix, if any
if platform == 'cygwin':