code
stringlengths
1
1.72M
language
stringclasses
1 value
import os import threading import Queue import traceback import atexit import weakref import __future__ # note that the whole code of this module (as well as some # other modules) execute not only on the local side but # also on any gateway's remote side. On such remote sides # we cannot assume the py library to be ...
Python
""" InputOutput Classes used for connecting gateways across process or computer barriers. """ import socket, os, sys class SocketIO: server_stmt = """ io = SocketIO(clientsock) import sys #try: # sys.stdout = sys.stderr = open('/tmp/execnet-socket-debug.log', 'a', 0) #except (IOError, OSError): # sys.st...
Python
""" ad-hoc networking mechanism """
Python
# Module doctest. # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org). # Major enhancements and refactoring by: # Jim Fulton # Edward Loper # Provided as-is; use at your own risk; no warranty; no promises; enjoy! r"""Module doctest -- a framework for running examples in docstrings. In...
Python
import py class Directory(py.test.collect.Directory): def run(self): py.test.skip("compat tests currently need to be run manually")
Python
# subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # This module should remain compatible with Python 2.2, see PEP 291. # # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> # # Licensed to PSF under a Contributor Agreement. # See http://ww...
Python
"""optparse - a powerful, extensible, and easy-to-use option parser. By Greg Ward <gward@python.net> Originally distributed as Optik; see http://optik.sourceforge.net/ . If you have problems with this module, please do not file bugs, patches, or feature requests with Python; instead, use Optik's SourceForge project ...
Python
#!/usr/bin/env python # # find and import a version of 'py' # import sys import os from os.path import dirname as opd, exists, join, basename, abspath def searchpy(current): while 1: last = current initpy = join(current, '__init__.py') if not exists(initpy): pydir = join(curre...
Python
#!/usr/bin/env python # # find and import a version of 'py' # import sys import os from os.path import dirname as opd, exists, join, basename, abspath def searchpy(current): while 1: last = current initpy = join(current, '__init__.py') if not exists(initpy): pydir = join(curre...
Python
#!/usr/bin/env python # # Test suite for Optik. Supplied by Johannes Gijsbers # (taradino@softhome.net) -- translated from the original Optik # test suite to this PyUnit-based version. # # $Id: test_optparse.py 46506 2006-05-28 18:15:43Z armin.rigo $ # import sys import os import copy import unittest from cStringIO...
Python
#
Python
"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward <gward@python.net> __revision__ = "$Id: textwrap.py 36379 2007-01-09 16:55:49Z cfbolz $" import string, re # Do the right thing with boolean values for all known...
Python
""" compatibility modules (taken from 2.4.4) """
Python
# # a generic conversion serializer # from py.xml import escape class SimpleUnicodeVisitor(object): """ recursive visitor to write unicode. """ def __init__(self, write, indent=0, curindent=0, shortempty=True): self.write = write self.cache = {} self.visited = {} # for detection of...
Python
#
Python
import re class _escape: def __init__(self): self.escape = { u'"' : u'&quot;', u'<' : u'&lt;', u'>' : u'&gt;', u'&' : u'&amp;', u"'" : u'&apos;', } self.charef_rex = re.compile(u"|".join(self.escape.keys())) def _replacer(self, match): return self.es...
Python
""" """ from py.xml import Namespace, Tag from py.__.xmlobj.visit import SimpleUnicodeVisitor class HtmlVisitor(SimpleUnicodeVisitor): single = dict([(x, 1) for x in ('br,img,area,param,col,hr,meta,link,base,' 'input,frame').split(',')]) inline = dict([(x, 1) for ...
Python
""" generic (and pythonic :-) xml tag and namespace objects """ class Tag(list): class Attr(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __init__(self, *args, **kwargs): super(Tag, self).__init__(args) self.attr = self.Attr(**kwargs) de...
Python
""" small and mean xml/html generation """
Python
#pythonexecutables = ('python2.2', 'python2.3',) #pythonexecutable = 'python2.2' # in the future we want to be able to say here: #def setup_module(extpy): # mod = extpy.resolve() # mod.module = 23 # directory = pypath.root.dirpath() # default values for options (modified from cmdline) verbose = 0 nocapture =...
Python
""" module for win-specific local path stuff (implementor needed :-) """ import os import py from py.__.path.local.common import Stat class WinMixin: def _makestat(self, statresult): return Stat(self, statresult) def chmod(self, mode, rec=0): """ change permissions to the given mode. If mod...
Python
""" specialized local path implementation. This Path implementation offers some methods like chmod(), owner() and so on that may only make sense on unix. """ from __future__ import generators import sys, os, stat, re, atexit import py from py.__.path import common iswin32 = sys.platform == "win32" if iswin32: ...
Python
#
Python
""" module to access local filesystem pathes (mostly filename manipulations but also file operations) """ import os, sys, stat import py #__________________________________________________________ # # Local Path Posix Mixin #__________________________________________________________ from py.__.path.local.common impor...
Python
import py class Stat(object): def __init__(self, path, osstatresult): self.path = path self._osstatresult = osstatresult for name in ('atime blksize blocks ctime dev gid ' 'ino mode mtime nlink rdev size uid'.split()): code = """if 1: def fget(s...
Python
#
Python
import py from py.__.path.testing import common def setuptestfs(path): if path.join('samplefile').check(): return #print "setting up test fs for", repr(path) samplefile = path.ensure('samplefile') samplefile.write('samplefile\n') execfile = path.ensure('execfile') execfile.write('x=42...
Python
from py.__.path.common import checker import py class CommonPathTests(object): root = None # subclasses have to setup a 'root' attribute def test_constructor_equality(self): p = self.root.__class__(self.root) assert p == self.root def test_eq_nonstring(self): path1 = self.root.jo...
Python
#
Python
""" module with base functionality for std.path package """ from __future__ import generators import os, sys import py def checktype(pathinstance, kw): names = ('local', 'svnwc', 'svnurl', 'py', ) for name,value in kw.items(): if name in names: cls = getattr(py.path, name) if b...
Python
""" module defining a subversion path object based on the external command 'svn'. """ import os, sys, time, re, calendar import py from py import path, process from py.__.path import common from py.__.path.svn import svncommon from py.__.misc.cache import BuildcostAccessCache, AgingCache DEBUG=False class SvnComm...
Python
""" module with a base subversion path object. """ import os, sys, time, re, string import py from py.__.path import common ALLOWED_CHARS = "_ -/\\=$.~+" #add characters as necessary when tested if sys.platform == "win32": ALLOWED_CHARS += ":" ALLOWED_CHARS_HOST = ALLOWED_CHARS + '@:' def _getsvnversion(ver=[...
Python
import sys import py from py import path, test, process from py.__.path.testing.fscommon import CommonFSTests, setuptestfs from py.__.path.svn import cache, svncommon mypath = py.magic.autopath() repodump = mypath.dirpath('repotest.dump') # make a wc directory out of a given root url # cache previously obtained wcs! ...
Python
#
Python
""" svn-Command based Implementation of a Subversion WorkingCopy Path. SvnWCCommandPath is the main class. SvnWC is an alias to this class. """ import os, sys, time, re, calendar import py from py.__.path import common from py.__.path.svn import cache from py.__.path.svn import svncommon DEBUG = 0 rex_blame...
Python
#
Python
""" # generic cache mechanism for subversion-related structures # XXX make mt-safe """ import time proplist = {} info = {} entries = {} prop = {} #----------------------------------------------------------- # Caching latest repository revision and repo-paths # (getting them is slow with the current implementations) ...
Python
""" unified file system api """
Python
import py, itertools from py.__.path import common COUNTER = itertools.count() class RemotePath(common.FSPathBase): sep = '/' def __init__(self, channel, id, basename=None): self._channel = channel self._id = id self._basename = basename self._specs = {} def __del__(self)...
Python
import threading class PathServer: def __init__(self, channel): self.channel = channel self.C2P = {} self.next_id = 0 threading.Thread(target=self.serve).start() def p2c(self, path): id = self.next_id self.next_id += 1 self.C2P[id] = path retur...
Python
#
Python
import py from remotepath import RemotePath SRC = open('channeltest.py', 'r').read() SRC += ''' import py srv = PathServer(channel.receive()) channel.send(srv.p2c(py.path.local("/tmp"))) ''' #gw = py.execnet.SshGateway('codespeak.net') gw = py.execnet.PopenGateway() c = gw.remote_exec(SRC) subchannel = gw.channelf...
Python
""" package initialization. You use the functionality of this package by putting from py.initpkg import initpkg initpkg(__name__, exportdefs={ 'name1.name2' : ('./path/to/file.py', 'name') ... }) into your package's __init__.py file. This will lead your package to only expose the names o...
Python
#!/usr/bin/env python import sys, os, os.path progpath = sys.argv[0] packagedir = os.path.abspath(os.path.dirname(progpath)) packagename = os.path.basename(packagedir) bindir = os.path.join(packagedir, 'bin') if sys.platform == 'win32': bindir = os.path.join(bindir, 'win32') rootdir = os.path.dirname(packagedir) ...
Python
#
Python
""" high-level sub-process handling """
Python
""" module defining basic hook for executing commands in a - as much as possible - platform independent way. Current list: exec_cmd(cmd) executes the given command and returns output or ExecutionFailed exception (if exit status!=0) """ import os, sys import py #------------------...
Python
#!/usr/bin/python import py for x in py.path.local(): if x.ext == '.txt': cmd = ("python /home/hpk/projects/docutils/tools/rst2s5.py " "%s %s" %(x, x.new(ext='.html'))) print "execing", cmd py.std.os.system(cmd)
Python
import py py.magic.autopath() import py pydir = py.path.local(py.__file__).dirpath() distdir = pydir.dirpath() dist_url = 'http://codespeak.net/svn/py/dist/' #issue_url = 'http://codespeak.net/issue/py-dev/' docdir = pydir.join('documentation') reffile = docdir / 'talk' / '_ref.txt' linkrex = py.std.re.compile('...
Python
#!/usr/bin/python import py for x in py.path.local(): if x.ext == '.txt': cmd = ("python /home/hpk/projects/docutils/tools/rst2s5.py " "%s %s" %(x, x.new(ext='.html'))) print "execing", cmd py.std.os.system(cmd)
Python
import py from py.__.misc.rest import convert_rest_html, strip_html_header from py.__.misc.difftime import worded_time from py.__.doc.conftest import get_apigenpath, get_docpath from py.__.apigen.linker import relpath html = py.xml.html class Page(object): doctype = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...
Python
from __future__ import generators import py from py.__.misc import rest from py.__.apigen.linker import relpath import os pypkgdir = py.path.local(py.__file__).dirpath() mypath = py.magic.autopath().dirpath() Option = py.test.config.Option option = py.test.config.addoptions("documentation check options", ...
Python
#
Python
import py html = py.xml.html class my(html): "a custom style" class body(html.body): style = html.Style(font_size = "120%") class h2(html.h2): style = html.Style(background = "grey") class p(html.p): style = html.Style(font_weight="bold") doc = my.html( my.head(), ...
Python
from py.test import raises import py def otherfunc(a,b): assert a==b def somefunc(x,y): otherfunc(x,y) def otherfunc_multi(a,b): assert (a == b) class TestFailing(object): def test_simple(self): def f(): return 42 def g(): return 43 ass...
Python
from py.xml import html paras = "First Para", "Second para" doc = html.html( html.head( html.meta(name="Content-Type", value="text/html; charset=latin1")), html.body( [html.p(p) for p in paras])) print unicode(doc).encode('latin1')
Python
import py class ns(py.xml.Namespace): pass doc = ns.books( ns.book( ns.author("May Day"), ns.title("python for java programmers"),), ns.book( ns.author("why", class_="somecssclass"), ns.title("Java for Python programmers"),), publisher="N.N", ) print doc.uni...
Python
"""Defines a safe repr function. This will always return a string of "reasonable" length no matter what the object does in it's own repr function. Let's examine what can go wrong in an arbitrary repr function. The default repr will return something like (on Win32 anyway): <foo.bar object at 0x008D5650>. Well behaved us...
Python
from __future__ import generators import py class TracebackEntry(object): """ a single entry in a traceback """ exprinfo = None def __init__(self, rawentry): self._rawentry = rawentry self.frame = py.code.Frame(rawentry.tb_frame) self.lineno = rawentry.tb_lineno - 1 ...
Python
from __future__ import generators import sys import inspect, tokenize import py cpy_compile = compile # DON'T IMPORT PY HERE class Source(object): """ a mutable object holding a source code fragment, possibly deindenting it. """ def __init__(self, *parts, **kwargs): self.lines = lines = [...
Python
#
Python
import py class Code(object): """ wrapper around Python code objects """ def __init__(self, rawcode): rawcode = getattr(rawcode, 'im_func', rawcode) rawcode = getattr(rawcode, 'func_code', rawcode) self.raw = rawcode self.filename = rawcode.co_filename try: ...
Python
from __future__ import generators import sys import py class ExceptionInfo(object): """ wraps sys.exc_info() objects and offers help for navigating the traceback. """ _striptext = '' def __init__(self, tup=None, exprinfo=None): # NB. all attributes are private! Subclasses or other ...
Python
""" python inspection/code generation API """
Python
import py import py.__.code.safe_repr class Frame(object): """Wrapper around a Python frame holding f_locals and f_globals in which expressions can be evaluated.""" def __init__(self, frame): self.code = py.code.Code(frame.f_code) self.lineno = frame.f_lineno - 1 self.f_globals = f...
Python
#!/usr/bin/env python import sys, os, os.path progpath = sys.argv[0] packagedir = os.path.abspath(os.path.dirname(progpath)) packagename = os.path.basename(packagedir) bindir = os.path.join(packagedir, 'bin') if sys.platform == 'win32': bindir = os.path.join(bindir, 'win32') rootdir = os.path.dirname(packagedir) ...
Python
import thread class ThreadOut(object): """ A file like object that diverts writing operations to per-thread writefuncs. This is a py lib internal class and not meant for outer use or modification. """ def __new__(cls, obj, attrname): """ Divert file output to per-thre...
Python
import Queue import threading import time import sys ERRORMARKER = object() class Reply(object): """ reply instances provide access to the result of a function execution that got dispatched through WorkerPool.dispatch() """ _excinfo = None def __init__(self, task): self....
Python
#
Python
#
Python
"""Classes to represent arbitrary sets (including sets of sets). This module implements sets using dictionaries whose values are ignored. The usual operations (union, intersection, deletion, etc.) are provided as both methods and operators. Important: sets are not sequences! While they support 'x in s', 'len(s)', a...
Python
builtin_cmp = cmp # need to use cmp as keyword arg def _sorted(iterable, cmp=None, key=None, reverse=0): use_cmp = None if key is not None: if cmp is None: def use_cmp(x, y): return builtin_cmp(x[0], y[0]) else: def use_cmp(x, y): return c...
Python
from __future__ import generators try: reversed = reversed except NameError: def reversed(sequence): """reversed(sequence) -> reverse iterator over values of the sequence Return a reverse iterator """ if hasattr(sequence, '__reversed__'): return sequence.__reversed_...
Python
try: BaseException = BaseException except NameError: BaseException = Exception
Python
#
Python
""" backports and additions of builtins """
Python
from __future__ import generators try: enumerate = enumerate except NameError: def enumerate(iterable): i = 0 for x in iterable: yield i, x i += 1
Python
#!/usr/bin/python import cgitb;cgitb.enable() import path import py from py.__.apigen.source.browser import parse_path from py.__.apigen.source.html import create_html, create_dir_html, \ create_unknown_html BASE_URL='http://codespeak.net/svn/py/dist' def cgi_main(): import os...
Python
""" simple Python syntax coloring """ import re class PythonSchema(object): """ contains information for syntax coloring """ comment = [('#', '\n'), ('#', '$')] multiline_string = ['"""', "'''"] string = ['"""', "'''", '"', "'"] keyword = ['and', 'break', 'continue', 'elif', 'else', 'except', ...
Python
#!/usr/bin/python import cgitb;cgitb.enable() import path import py from py.__.apigen.source.browser import parse_path from py.__.apigen.source.html import create_html, create_dir_html, \ create_unknown_html BASE_URL='http://codespeak.net/svn/py/dist' def cgi_main(): import os...
Python
""" web server for displaying source """ import py from pypy.translator.js.examples import server from py.__.apigen.source.browser import parse_path from py.__.apigen.source.html import create_html, create_dir_html, create_unknown_html from py.xml import html class Handler(server.TestHandler): BASE_URL='http://c...
Python
""" source browser using compiler module WARNING!!! This is very simple and very silly attempt to make so. """ from compiler import parse, ast import py from py.__.path.common import PathBase blockers = [ast.Function, ast.Class] class BaseElem(object): def listnames(self): if getattr(self, 'parent',...
Python
import os, sys sys.path = ['/'.join(os.path.dirname(__file__).split(os.sep)[:-3])] + sys.path
Python
""" html - generating ad-hoc html out of source browser """ import py from py.xml import html, raw from compiler import ast import time from py.__.apigen.source.color import Tokenizer, PythonSchema class HtmlEnchanter(object): def __init__(self, mod): self.mod = mod self.create_caches() ...
Python
import py import os html = py.xml.html # this here to serve two functions: first it makes the proto part of the temp # urls (see TempLinker) customizable easily (for tests and such) and second # it makes sure the temp links aren't replaced in generated source code etc. # for this file (and its tests) itself. TEMPLINK_...
Python
import py Option = py.test.config.Option option = py.test.config.addoptions("apigen test options", Option('', '--webcheck', action="store_true", dest="webcheck", default=False, help="run XHTML validation tests" ), )
Python
""" layout definition for generating api/source documents this is the place where customization can be done """ import py from py.__.doc import confrest from py.__.apigen import linker from py.__.doc.conftest import get_apigenpath, get_docpath here = py.magic.autopath().dirpath() class LayoutPage(confrest.PyPag...
Python
""" run 'py.test --apigen=<this script>' to get documentation exported """ import os import py import sys from py.__.apigen import htmlgen from py.__.apigen import linker from py.__.apigen import project from py.__.apigen.tracer.docstorage import pkg_to_dict from py.__.doc.conftest import get_apigenpath from layout i...
Python
import py import os import inspect from py.__.apigen.layout import LayoutPage from py.__.apigen.source import browser as source_browser from py.__.apigen.source import html as source_html from py.__.apigen.source import color as source_color from py.__.apigen.tracer.description import is_private from py.__.apigen.rest....
Python
""" Generating ReST output (raw, not python) out of data that we know about function calls """ import py import sys import re from py.__.apigen.tracer.docstorage import DocStorageAccessor from py.__.rest.rst import * # XXX Maybe we should list it here from py.__.apigen.tracer import model from py.__.rest.transform i...
Python
from py.__.rest.transform import HTMLHandler, entitize from py.xml import html, raw class PageHandler(HTMLHandler): def startDocument(self): super(PageHandler, self).startDocument() self.head.append(html.link(type='text/css', rel='stylesheet', href='style.css')) ...
Python
class SomeClass(object): """Some class definition""" def __init__(self, a): self.a = a def method(self, a, b, c): """method docstring""" return a + b + c
Python
from somemodule import SomeClass class SomeSubClass(SomeClass): """Some subclass definition""" def fun(a, b, c): """Some docstring Let's make it span a couple of lines to be interesting... Note: * rest * should * be * supported * or ...
Python
import py from py.__.apigen.tracer import model from py.__.code.source import getsource import types import inspect import copy MAX_CALL_SITES = 20 set = py.builtin.set def is_private(name): return name.startswith('_') and not name.startswith('__') class CallFrame(object): def __init__(self, frame): ...
Python
import py class DescPlaceholder(object): pass class ClassPlaceholder(object): pass class SerialisableClassDesc(object): def __init__(self, original_desc): self.is_degenerated = original_desc.is_degenerated self.name = original_desc.name class PermaDocStorage(object): """ Picklable ve...
Python
""" simple tracer for API generation """ import py import sys import types from py.__.apigen.tracer.description import FunctionDesc from py.__.apigen.tracer.docstorage import DocStorage class UnionError(Exception): pass class NoValue(object): pass class Tracer(object): """ Basic tracer object, used fo...
Python
""" model - type system model for apigen """ # we implement all the types which are in the types.*, naming # scheme after pypy's import py import types set = py.builtin.set # __extend__ and pairtype? class SomeObject(object): typedef = types.ObjectType def __repr__(self): return "<%s>" % self...
Python
""" This module is keeping track about API informations as well as providing some interface to easily access stored data """ import py import sys import types import inspect from py.__.apigen.tracer.description import FunctionDesc, ClassDesc, \ MethodDesc, Desc from py.__...
Python
def cut_pyc(f_name): if f_name.endswith('.pyc'): return f_name[:-1] return f_name
Python
def foo(x): return x + 1 def bar(x): return x + 2
Python