Source code for compat

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2014, Wolfgang Scherer, <Wolfgang.Scherer at gmx.de>
#
# This file is part of PyJsMo.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Alternatively, permisssion is granted to use this file under the
# provisions of the MIT license:
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""\
compat.py - Python 2/3 compatibility

======  ====================
usage:  compat.py [OPTIONS]
or      import compat
======  ====================

Options
=======

  ===================== ==================================================
  -q, --quiet           suppress warnings
  -v, --verbose         verbose test output
  -d, --debug[=NUM]     show debug information
  -h, --help            display this help message

  --template list       show available templates.
  --eide[=COMM]         Emacs IDE template list (implies --template list).
  --template[=NAME]     extract named template to standard
                        output. Default NAME is ``-``.
  --extract[=DIR]       extract adhoc files to directory DIR (default: ``.``)
  --explode[=DIR]       explode script with adhoc in directory DIR
                        (default ``__adhoc__``)
  --implode             implode script with adhoc

  -t, --test            run doc tests
  ===================== ==================================================

Module
======

PyJsMo internal import template:

.. @:adhoc_template:@ -compat-import

>>>
_pyjsmo_loaded_ = False
try:
    exec("from .compat import *")
    exec("from .base import PyJsMo")
    _pyjsmo_loaded_ = True
except (SyntaxError, SystemError, ValueError, ImportError):
    pass
if not _pyjsmo_loaded_:
    from pyjsmo.compat import *
    from pyjsmo.base import PyJsMo
del(globals()['_pyjsmo_loaded_'])

.. @:adhoc_template:@ -compat-import

Exports
-------

>>> for ex in __all__:
...     printf(sformat('from {0} import {1}', __name__, ex))
from compat import printf
from compat import sformat
from compat import isstring
from compat import issequence
from compat import sequence_type
from compat import UCHAR_FMT
from compat import uchar
from compat import ditems
from compat import dkeys
from compat import dvalues
from compat import xfilter
from compat import xmap
from compat import lfind
from compat import dbg_comm
from compat import dbg_twid
from compat import dbg_fwid
from compat import _canonize_module_
from compat import uc_type
from compat import ucs
from compat import u8s
from compat import nts
from compat import OrderedDict
from compat import BytesIO
from compat import StringIO
from compat import BytesIOIType
from compat import StringIOIType
from compat import filterl
from compat import printe_

.. _END_OF_HELP_compat:
"""

# (progn (forward-line 1) (snip-insert "py.b.future.with" t t "python") (insert "\n"))
# for python 2.5
from __future__ import with_statement

# (progn (forward-line 1) (snip-insert "py.main.pyramid.activate" t t "py") (insert ""))

__all__ = []

# --------------------------------------------------
# |||:sec:||| COMPATIBILITY
# --------------------------------------------------

import sys
# (progn (forward-line 1) (snip-insert "py.b.printf" t t "py") (insert "\n"))
# adapted from http://www.daniweb.com/software-development/python/code/217214
try:
    printf = eval("print") # python 3.0 case
except SyntaxError:
    printf_dict = dict()
    try:
        exec("from __future__ import print_function\nprintf=print", printf_dict)
        printf = printf_dict["printf"] # 2.6 case
    except SyntaxError:
        def printf(*args, **kwd): # 2.4, 2.5, define our own Print function
            fout = kwd.get("file", sys.stdout)
            w = fout.write
            if args:
                w(str(args[0]))
            sep = kwd.get("sep", " ")
            for a in args[1:]:
                w(sep)
                w(str(a))
            w(kwd.get("end", "\n"))
    del printf_dict

# (progn (forward-line 1) (snip-insert "py.b.sformat" t t "py") (insert "\n"))
try:
    ('{0}').format(0)
    def sformat (fmtspec, *args, **kwargs):
        return fmtspec.format(*args, **kwargs)
except AttributeError:
    try:
        import stringformat
        def sformat (fmtspec, *args, **kwargs):
            return stringformat.FormattableString(fmtspec).format(
                *args, **kwargs)
    except ImportError:
        printf('error: stringformat missing. Try `easy_install stringformat`.', file=sys.stderr)

# (progn (forward-line 1) (snip-insert "py.b.isstring" t t "python") (insert "\n"))
try:
    from ws_seq_type import isstring, issequence, sequence_type, UCHAR_FMT
except ImportError:
    # (progn (forward-line 1) (snip-insert "py.f.isstring" t t "py") (insert "\n"))
    exec('''
    def isstring(obj):
        return isinstance(obj, basestring)
    '''.strip())
    try:
        isstring("")
        UCHAR_FMT = 'u"{0}u{1:04x}"'
    except NameError:
        def isstring(obj):
            return isinstance(obj, str) or isinstance(obj, bytes)
        UCHAR_FMT = '"{0}u{1:04x}"'
    # (progn (forward-line 1) (snip-insert "py.f.issequence" t t "py") (insert "\n"))
    def issequence(arg, or_dict=False, or_seq=True):           # ||:fnc:||
        if not isstring(arg):
            if hasattr(arg, 'items'):
                return or_dict
            if hasattr(arg, '__getitem__'):
                return True
            if hasattr(arg, '__iter__'):
                return or_seq
        return False
    # (progn (forward-line 1) (snip-insert-mode "py.f.sequence_type" t) (insert "\n"))
    _st_strg = (True,  False, False, False)
    _st_list = (False, True,  False, False)
    _st_dict = (False, False, True,  False)
    _st_seq  = (False, False, False, True)
    _st_none = (False, False, False, False)
    def sequence_type(value):                                  # ||:fnc:||
        if isstring(value):
            return _st_strg
        if hasattr(value, 'items'):
            return _st_dict
        if hasattr(value, '__getitem__'):
            return _st_list
        if hasattr(value, '__iter__'):
            return _st_seq
        return _st_none

# ws_seq_type 0.1.1 compatibility
try:
    is_string, is_list, is_dict, is_seq = sequence_type(())
except ValueError:
    sequence_type__ = sequence_type
    def sequence_type(obj):
        result = list(sequence_type__(obj))
        result.append(hasattr(obj, '__iter__'))
        return result

[docs]def uchar(num): '''Make UNICODE character.''' return eval(sformat(UCHAR_FMT,'\\', num))
# (progn (forward-line 1) (snip-insert "py.b.dict.items" t t "py") (insert "\n")) try: getattr(dict(), 'iteritems') except AttributeError: ditems = lambda d: getattr(d, 'items')() dkeys = lambda d: getattr(d, 'keys')() dvalues = lambda d: getattr(d, 'values')() else: ditems = lambda d: getattr(d, 'iteritems')() dkeys = lambda d: getattr(d, 'iterkeys')() dvalues = lambda d: getattr(d, 'itervalues')() __all__.extend(( 'printf', 'sformat', 'isstring', 'issequence', 'sequence_type', 'UCHAR_FMT', 'uchar', 'ditems', 'dkeys', 'dvalues', )) # (progn (forward-line 1) (snip-insert "py.b.xrange" t t "py") (insert "\n")) # `xrange` returns a generator, which `range` already does for python3 try: xrange(0) except NameError: xrange = range __all__.append('xrange') # `xfilter` returns a list, `filter` may return a generator. This is # different from the range/xrange semantics! if isinstance(filter(str, []), list): xfilter = filter else: xfilter = lambda *args, **kwargs: list(filter(*args, **kwargs)) # `xmap` returns a list, `map` may return a generator. This is # different from the range/xrange semantics! if isinstance(map(str, []), list): xmap = map else: xmap = lambda *args, **kwargs: list(map(*args, **kwargs)) __all__.extend(( 'xfilter', 'xmap', )) # `long` is gone in python3 try: isinstance(int, long) except NameError: long = int __all__.append('long') # (progn (forward-line 1) (snip-insert "py_f.lfind" t t "python") (insert "\n")) def lfind(l, elt): try: return l.index(elt) except ValueError: return -1 __all__.extend(( 'lfind', )) import os import re # -------------------------------------------------- # |||:sec:||| CONFIGURATION # -------------------------------------------------- # (progn (forward-line 1) (snip-insert "py.b.dbg.def" t t "python") (insert "")) dbg_comm = ((('dbg_comm' not in globals()) and ('# ')) or (globals()['dbg_comm'])) dbg_twid = ((('dbg_twid' not in globals()) and (9)) or (globals()['dbg_twid'])) dbg_fwid = ((('dbg_fwid' not in globals()) and (15)) or (globals()['dbg_fwid'])) __all__.extend(( 'dbg_comm', 'dbg_twid', 'dbg_fwid', )) # (progn (forward-line 1) (snip-insert "py.b.canonize.module" t t "python") (insert "")) def _canonize_module_(module_or_name, full=None, drop=None): """Set module's ``_is_main_`` flag/register module under canonical name. :param full: if not True, only set ``_is_main_`` flag. Otherwise, register module under canonical name. This is useful, for e.g. consistent _pyjsmo_class resolution. :param drop: drop this many trailing parts of the canonical module name. E.g., `pyjsmo.table.tbase` => `pyjsmo.table`. .. note:: After full canonization, the idiom | ``if __name__ == '__main__: ...'`` no longer works. Use | ``if globals().get('_is_main_', (__name__ == '__main__')): ...`` instead. """ if isstring(module_or_name): module = sys.modules[module_or_name] else: module = module_or_name module_name = module.__name__ # flag for __main__ _is_main_ = (module_name == '__main__') if not hasattr(module, '_is_main_'): module._is_main_ = _is_main_ if not full: return _is_main_ # module file name -> canonical name try: mfile = module.__file__ except AttributeError: return canon_name_ = mfile canon_name_ = os.path.basename(canon_name_) canon_name_, _ext = os.path.splitext(canon_name_) # adhoc compiliation xx_.py -> xx.py if canon_name_.endswith('_') and not canon_name_.endswith('__'): canon_name_ = canon_name_[:-1] # find parent module |:check:| distutils/pkg_resources? mdir = os.path.abspath(os.path.dirname(mfile)) mparts = [] while mdir and os.path.exists(os.path.join(mdir, '__init__.py')): mdir, pfx = os.path.split(mdir) mparts.insert(0, pfx) parent = '.'.join(mparts) if canon_name_ != '__init__': mparts.append(canon_name_) if drop: mparts = mparts[:-drop] canon_name = '.'.join(mparts) if module_name != canon_name: if parent != canon_name or drop: # |:check:| why? if parent: # fix parent module exec('import ' + parent) if parent in (sys.modules): setattr(sys.modules[parent], canon_name_, module) sys.modules[canon_name] = module module.__name__ = canon_name # adjust module members for t in dvalues(vars(module)): try: if '__module__' in vars(t) and t.__module__ == module_name: t.__module__ = canon_name except TypeError: pass return _is_main_ #_canonize_module_(__name__, __name__ == '__main__') __all__.extend(( '_canonize_module_', )) # (progn (forward-line 1) (snip-insert "py.b.strings" t t "py") (insert "\n")) def _ucs(string, charset=None): # ||:fnc:|| return unicode(string, charset or 'utf-8') try: _ucs("") except NameError: _ucs = lambda s, c=None: s.decode(c or 'utf-8') try: exec('uc_type = type(_ucs(b""))') except SyntaxError: uc_type = type(_ucs(""))
[docs]def ucs(value, charset=None): # ||:fnc:|| """\ Convert `value` to unicode string using charset or UTF-8, if `value` is a string. If `value` is not a string, or if it is already a unicode string, return it unmodified. """ if isstring(value) and not isinstance(value, uc_type): return _ucs(value, charset) return value
[docs]def u8s(string, encoding=None): # ||:fnc:|| """\ Convert `string` to UTF-8-encoded byte string, if `string` is a unicode string. If `string` is not a unicode string, return it unmodified. """ if isinstance(string, uc_type): return string.encode(encoding or 'utf-8') return string
[docs]def nts(string): # ||:fnc:|| """\ Convert string to native string, if applicable. Python2 native strings are byte strings, while Python3 native strings are unicode. """ # for python3, unicode strings have type str if isinstance(string, str): return string # for python2, encode unicode strings to utf-8 strings if isinstance(string, uc_type): return string.encode('utf-8') if isstring(string): try: return str(string.decode('utf-8')) except UnicodeDecodeError: #return str(string.decode('latin1')) pass return string
__all__.extend(( 'uc_type', 'ucs', 'u8s', 'nts', )) # (progn (forward-line 1) (snip-insert "py.f.strclean" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.b.logging" t t "python") (insert "")) # (progn (forward-line 1) (snip-insert "py.b.ordereddict" t t "py") (insert "\n")) try: from collections import OrderedDict except ImportError: try: from ordereddict import OrderedDict except ImportError: printf('error: ordereddict missing. Try `easy_install ordereddict`.', file=sys.stderr) sys.exit(1) import collections collections.OrderedDict = OrderedDict __all__.extend(( 'OrderedDict', )) # (progn (forward-line 1) (snip-insert "py.b.stringio" t t "py") (insert "\n")) try: from cStringIO import StringIO as BytesIO, StringIO except ImportError: try: from io import BytesIO, StringIO except ImportError: from StringIO import StringIO as BytesIO, StringIO BytesIOIType = type(BytesIO(b'')) StringIOIType = type(StringIO('')) __all__.extend(( 'BytesIO', 'StringIO', 'BytesIOIType', 'StringIOIType', )) # (progn (forward-line 1) (snip-insert "py.b.dbg.setup" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.main.project.libdir" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.main.sql.alchemy" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.main.sql.ws" t t "py") (insert "\n")) # @:adhoc_run_time:@ #import adhoc # @:adhoc:@ # (progn (forward-line 1) (snip-insert "py.b.posix" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.b.os.system.sh" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.b.prog.path" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.b.line.loop" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.wsrfid.pylons.imports" t t "python") (insert "")) # (progn (forward-line 1) (snip-insert "py.main.wsgi.get.app" t t "python") (insert "")) # deprecated filterl = xfilter __all__.extend(( 'filterl', )) # -------------------------------------------------- # |||:sec:||| CLASSES # -------------------------------------------------- # (progn (forward-line -1) (insert "\n") (snip-insert "py.s.class" t t "py") (backward-symbol-tag 1 "fillme" "::")) # -------------------------------------------------- # |||:sec:||| FUNCTIONS # -------------------------------------------------- # (progn (forward-line -1) (insert "\n") (snip-insert "py.s.func" t t "py") (backward-symbol-tag 1 "fillme" "::")) # (progn (forward-line 1) (snip-insert "py.wsrfid.module.route" t t "py") (insert "")) # -------------------------------------------------- # |||:sec:||| UTILITIES # -------------------------------------------------- # (progn (forward-line 1) (snip-insert "py.wsrfid.dispatch.request" t t "py") (insert "")) # (progn (forward-line 1) (snip-insert "py.f.findfile" t t "py") (insert "")) # (progn (forward-line 1) (snip-insert "py.c.placeholder.template" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.c.key.hash.ordered.dict" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.c.progress" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.hl" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.single.quote" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.remove.match" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.printenv" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.uname.s" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.printe" t t "py") (insert "")) def printe_(*args, **kwargs): kwargs['file'] = kwargs.get('file', sys.stderr) printf(*args, **kwargs) if 'printe' not in globals(): # or globals().get('_is_main_', (__name__ == '__main__')): printe = printe_ printd = printe_ printw = printe_ printx = printe_ __all__.extend(( 'printe_', )) # (progn (forward-line 1) (snip-insert "py.f.dbg.squeeze" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.f.dbg.indent" t t "py") (insert "\n")) def run(parameters): # ||:fnc:|| """Application runner, when called as __main__.""" # (progn (forward-line 1) (snip-insert "py.bf.sql.ws" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.bf.file.arg.loop" t t "py") (insert "\n")) # (progn (forward-line 1) (snip-insert "py.wsrfid.wsuvv.run" t t "py") (insert "\n")) # |:here:| pass # -------------------------------------------------- # |||:sec:||| MAIN # -------------------------------------------------- _quiet = False _verbose = False _debug = False # (progn (forward-line 1) (snip-insert "py.f.setdefaultencoding" t t "py") (insert "\n")) file_encoding_is_clean = False def setdefaultencoding(encoding=None, quiet=False): if file_encoding_is_clean: return if encoding is None: encoding='utf-8' try: isinstance('', basestring) if not hasattr(sys, '_setdefaultencoding'): if not quiet: printf('''\ Add this to /etc/python2.x/sitecustomize.py, or put it in local sitecustomize.py and adjust PYTHONPATH=".:${PYTHONPATH}":: try: import sys setattr(sys, '_setdefaultencoding', getattr(sys, 'setdefaultencoding')) except AttributeError: pass Running with reload(sys) hack ... ''', file=sys.stderr) reload(sys) setattr(sys, '_setdefaultencoding', getattr(sys, 'setdefaultencoding')) sys._setdefaultencoding(encoding) except NameError: # python3 already has utf-8 default encoding ;-) pass def main(argv): # ||:fnc:|| global _quiet, _debug, _verbose global RtAdHoc, AdHoc try: import argparse except ImportError: printe('error: argparse missing. Try `easy_install argparse`.') sys.exit(1) parser = argparse.ArgumentParser(add_help=False) # parser.add_argument('--sum', dest='accumulate', action='store_const', # const=sum, default=max, # help='sum the integers (default: find the max)') # |:opt:| add options parser.add_argument( '-q', '--quiet', action='store_const', const=-2, dest='debug', default=0, help='suppress warnings') parser.add_argument( '-v', '--verbose', action='store_const', const=-1, dest='debug', default=0, help='verbose test output') parser.add_argument( '-d', '--debug', nargs='?', action='store', type=int, metavar='NUM', default = 0, const = 1, help='show debug information') parser.add_argument( '-t', '--test', action='store_true', help='run doc tests') class AdHocAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): list(map(lambda opt: setattr(namespace, opt, False), ('implode', 'explode', 'extract', 'template', 'eide'))) setattr(namespace, option_string[2:], True) setattr(namespace, 'adhoc_arg', values) parser.add_argument( '--implode', nargs=0, action=AdHocAction, default=False, help='implode script with adhoc') parser.add_argument( '--explode', nargs='?', action=AdHocAction, type=str, metavar='DIR', default=False, const='__adhoc__', help='explode script with adhoc in directory DIR' ' (default: `__adhoc__`)') parser.add_argument( '--extract', nargs='?', action=AdHocAction, type=str, metavar='DIR', default=False, const = '.', help='extract files to directory DIR (default: `.`)') parser.add_argument( '--template', nargs='?', action=AdHocAction, type=str, metavar='NAME', default=False, const = '-', help='extract named template to standard output. default NAME is ``-``') parser.add_argument( '--eide', nargs='?', action=AdHocAction, type=str, metavar='COMM', default=False, const = '', help='Emacs IDE template list (implies --template list).') parser.add_argument( '-h', '--help', action='store_true', help="display this help message") parser.add_argument( '--ap-help', action='store_true', help="internal help message") if True: # all options and arguments are known # all non-option arguments are consumed by `_parameters.args` parser.add_argument( 'args', nargs='*', metavar='arg', #'args', nargs='+', metavar='arg', #type=argparse.FileType('r'), default=sys.stdin, help='a series of arguments') _parameters = parser.parse_args(argv[1:]) else: # (progn (forward-line 1) (snip-insert "py_f.args_split_range" t t "python") (insert "\n")) def args_split_range(args): next_range = [] for arg in args: next_range.append(arg) if not arg.startswith('-'): break if next_range and not next_range[0].startswith('-'): next_range = [] return next_range, args[len(next_range):] # for sub-commands with their own options: pre-parse to first # non-option argument _parameters = None args = argv[1:] while True: next_range, args = args_split_range(args) if not next_range and not _parameters is None: break _parameters, unknown_args = parser.parse_known_args(next_range, _parameters) if unknown_args: unknown_args.extend(args) args = unknown_args next_range = [] break _parameters.args = args # generate argparse help if _parameters.ap_help: parser.print_help() return 0 # standard help if _parameters.help: help_ = re.sub('\n+[.][.] _END_OF_HELP.*(?s)', '', __doc__) sys.stdout.write(help_ + '\n') return 0 _debug = _parameters.debug if _debug > 0: _verbose = True _quiet = False elif _debug < 0: _verbose = (_debug == -1) _quiet = not(_verbose) _debug = 0 _parameters.debug = _debug _parameters.verbose = _verbose _parameters.quiet = _quiet if _debug: cmd_line = argv sys.stderr.write(sformat( "{0}{3:^{1}} {4:<{2}s}: ]{5!s}[\n", ((('dbg_comm' in globals()) and (globals()['dbg_comm'])) or ('# ')), ((('dbg_twid' in globals()) and (globals()['dbg_twid'])) or (9)), ((('dbg_fwid' in globals()) and (globals()['dbg_fwid'])) or (15)), ':DBG:', 'cmd_line', cmd_line)) # at least use `quiet` to suppress the setdefaultencoding warning setdefaultencoding(quiet=_quiet or _parameters.test) # |:opt:| handle options # adhoc: implode/explode/extract adhoc_export = (_parameters.explode or _parameters.extract) adhoc_op = ( _parameters.implode or adhoc_export or _parameters.template or _parameters.eide ) if adhoc_op: file_ = __file__ source = None have_adhoc = 'AdHoc' in globals() have_rt_adhoc = 'RtAdHoc' in globals() # shall adhoc be imported if _parameters.implode or not have_rt_adhoc: # shall this file be compiled adhoc_compile = not (have_rt_adhoc) os_path = os.defpath for pv in ('PATH', 'path'): try: os_path = os.environ[pv] break except KeyError: pass os_path = os_path.split(os.pathsep) for path_dir in os_path: if not path_dir: continue if path_dir not in sys.path: sys.path.append(path_dir) if not have_adhoc: try: import adhoc AdHoc = adhoc.AdHoc except ImportError: adhoc_compile = False try: from rt_adhoc import RtAdHoc as Adhoc except ImportError: pass else: adhoc_compile = False AdHoc = RtAdHoc AdHoc.quiet = _quiet AdHoc.verbose = _verbose AdHoc.debug = _debug AdHoc.include_path.append(os.path.dirname(file_)) AdHoc.extra_templates = [ ] AdHoc.template_process_hooks = { } if _parameters.eide: AdHoc.tt_ide = True AdHoc.tt_comment = _parameters.adhoc_arg or '' AdHoc.tt_prefix = '. (shell-command "' AdHoc.tt_suffix = '")' _parameters.template = True _parameters.adhoc_arg = 'list' if adhoc_compile: ah = AdHoc() source = ah.compileFile(file_) else: file_, source = AdHoc.std_source_param(file_) # implode if _parameters.implode: # @:adhoc_enable:@ # if not _quiet: # map(sys.stderr.write, # ["warning: ", os.path.basename(file_), # " already imploded!\n"]) # @:adhoc_enable:@ AdHoc.write_source('-', source) # explode elif _parameters.explode: AdHoc.export_dir = _parameters.adhoc_arg AdHoc.export(file_, source) # extract elif _parameters.extract: AdHoc.extract_dir = _parameters.adhoc_arg AdHoc.extract(file_, source) # template elif _parameters.template: template_name = _parameters.adhoc_arg if not template_name: template_name = '-' if template_name == 'list': sys.stdout.write( '\n'.join(AdHoc.template_table(file_, source)) + '\n') else: template = AdHoc.get_named_template( template_name, file_, source) AdHoc.write_source('-', template) # restore for subsequent calls to main if not have_adhoc: del(AdHoc) return 0 # run doc tests if _parameters.test: import doctest if globals().get('_canonize_module_'): _canonize_module_(__name__, __name__ == '__main__') try: logger = logging.getLogger() logger.setLevel(logging.DEBUG) except NameError: pass result = doctest.testmod(verbose = _verbose) return result.failed # |:opt:| handle options final = False ecode = 0 try: try: ecode = run(_parameters) except IOError: (t, e, tb) = sys.exc_info() del(tb) # ignore SIGPIPE import errno if e.errno != errno.EPIPE: raise except SystemExit: raise except: # |:info:| this is used, since module cgitb does not work so well ... (t, e, tb) = sys.exc_info() if not final or _debug: import traceback printf(''.join(traceback.format_tb(tb)), file=sys.stderr, end='') printf(sformat('{0}: {1}', t.__name__, e), file=sys.stderr) del(tb) ecode = 1 return ecode if globals().get('_is_main_', (__name__ == '__main__')): #sys.argv.insert(1, '--debug') # |:debug:| result = main(sys.argv) sys.exit(result) # |:here:| # (progn (forward-line 1) (snip-insert "py.t.ide" t t "py") (insert "\n")) # # :ide-menu: Emacs IDE Main Menu - Buffer @BUFFER@ # . M-x `eIDE-menu' (eIDE-menu "z") # :ide: CSCOPE ON # . (cscope-minor-mode) # :ide: CSCOPE OFF # . (cscope-minor-mode (quote ( nil ))) # :ide: TAGS: forced update # . (compile (concat "cd /home/ws/project/ws-rfid && make -k FORCED=1 tags")) # :ide: TAGS: update # . (compile (concat "cd /home/ws/project/ws-rfid && make -k tags")) # :ide: +-#+ # . Utilities () # :ide: TOC: Generate TOC with py-toc.py # . (progn (save-buffer) (compile (concat "py-toc.py ./" (file-name-nondirectory (buffer-file-name)) " "))) # :ide: CMD: Fold region with line continuation # . (shell-command-on-region (region-beginning) (region-end) "fold --spaces -width 79 | sed 's, $,,;1!s,^, ,;$!s,$,\\\\,'" nil nil nil t) # :ide: CMD: Fold region and replace with line continuation # . (shell-command-on-region (region-beginning) (region-end) "fold --spaces --width 79 | sed 's, $,,;1!s,^, ,;$!s,$,\\\\,'" t nil nil t) # :ide: +-#+ # . Fold () # :ide: CMD: Remove 8 spaces and add `>>> ' to region # . (shell-command-on-region (region-beginning) (region-end) "sed 's,^ ,,;/^[ ]*##/d;/^[ ]*#/{;s,^ *# *,,p;d;};/^[ ]*$/!s,^,>>> ,'" nil nil nil t) # :ide: CMD: Remove 4 spaces and add `>>> ' to region # . (shell-command-on-region (region-beginning) (region-end) "sed 's,^ ,,;/^[ ]*##/d;/^[ ]*#/{;s,^ *# *,,p;d;};/^[ ]*$/!s,^,>>> ,'" nil nil nil t) # :ide: +-#+ # . Doctest () # :ide: LINT: Check 80 column width ignoring IDE Menus # . (let ((args " | /srv/ftp/pub/check-80-col.sh -")) (compile (concat "sed 's,^\\(\\|. \\|.. \\|... \\)\\(:ide\\|[.] \\).*,,' " (buffer-file-name) " " args " | sed 's,^-," (buffer-file-name) ",'"))) # :ide: LINT: Check 80 column width # . (let ((args "")) (compile (concat "/srv/ftp/pub/check-80-col.sh " (buffer-file-name) " " args))) # :ide: +-#+ # . Lint Tools () # :ide: DELIM: @: SYM :@ @:fillme:@ adhoc tag # . (symbol-tag-normalize-delimiter (cons (cons nil "@:") (cons ":@" nil)) t) # :ide: +-#+ # . Delimiters () # :ide: COMPILE: Run with --ap-help # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --ap-help"))) # :ide: COMPILE: Run with --help # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --help"))) # :ide: COMPILE: Run with --test # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --test"))) # :ide: COMPILE: Run with --test --verbose # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --test --verbose"))) # :ide: COMPILE: Run with --debug # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --debug"))) # :ide: +-#+ # . Compile with standard arguments () # :ide: OCCUR-OUTLINE: Python Source Code # . (x-symbol-tag-occur-outline "sec" '("|||:" ":|||") (cons (cons "^\\([ \t\r]*\\(def\\|class\\)[ ]+\\|[A-Za-z_]?\\)" nil) (cons nil "\\([ \t\r]*(\\|[ \t]*=\\)"))) # :ide: MENU-OUTLINE: Python Source Code # . (x-eIDE-menu-outline "sec" '("|||:" ":|||") (cons (cons "^\\([ \t\r]*\\(def\\|class\\)[ ]+\\|[A-Za-z_]?\\)" nil) (cons nil "\\([ \t\r]*(\\|[ \t]*=\\)"))) # :ide: +-#+ # . Outline () # :ide: INFO: SQLAlchemy - SQL Expression Language - Reference # . (let ((ref-buffer "*sqa-expr-ref*")) (if (not (get-buffer ref-buffer)) (shell-command (concat "w3m -dump -cols " (number-to-string (1- (window-width))) " 'http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/expressions.html'") ref-buffer) (display-buffer ref-buffer t))) # :ide: INFO: SQLAlchemy - SQL Expression Language - Tutorial # . (let ((ref-buffer "*sqa-expr-tutor*")) (if (not (get-buffer ref-buffer)) (shell-command (concat "w3m -dump -cols " (number-to-string (1- (window-width))) " 'http://www.sqlalchemy.org/docs/05/sqlexpression.html'") ref-buffer) (display-buffer ref-buffer t))) # :ide: INFO: SQLAlchemy - Query # . (let ((ref-buffer "*sqa-query*")) (if (not (get-buffer ref-buffer)) (shell-command (concat "w3m -dump -cols " (number-to-string (1- (window-width))) " 'http://www.sqlalchemy.org/docs/orm/query.html'") ref-buffer) (display-buffer ref-buffer t))) # :ide: +-#+ # . SQLAlchemy Reference () # :ide: INFO: Python - argparse # . (let ((ref-buffer "*python-argparse*")) (if (not (get-buffer ref-buffer)) (shell-command (concat "w3m -dump -cols " (number-to-string (1- (window-width))) " 'http://docs.python.org/library/argparse.html'") ref-buffer) (display-buffer ref-buffer t))) # :ide: INFO: Python Documentation # . (let ((ref-buffer "*w3m*")) (if (get-buffer ref-buffer) (display-buffer ref-buffer t)) (other-window 1) (w3m-goto-url "http://docs.python.org/index.html" nil nil)) # :ide: INFO: Python Reference # . (let* ((ref-buffer "*python-ref*") (local "/home/ws/project/ws-util/python/reference/PQR2.7.html") (url (or (and (file-exists-p local) local) "'http://rgruet.free.fr/PQR27/PQR2.7.html'"))) (unless (get-buffer ref-buffer) (get-buffer-create ref-buffer) (with-current-buffer ref-buffer (shell-command (concat "snc txt.py.reference 2>/dev/null") ref-buffer) (goto-char (point-min)) (if (eobp) (shell-command (concat "w3m -dump -cols " (number-to-string (1- (window-width))) " " url) ref-buffer)))) (display-buffer ref-buffer t)) # :ide: +-#+ # . Python Reference () # :ide: COMPILE: Run with --eide # . (progn (save-buffer) (shell-command (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --eide") (concat "*templates: " (file-name-nondirectory (buffer-file-name)) "*"))) # :ide: COMPILE: Run with python3 --test # . (progn (save-buffer) (compile (concat "python3 ./" (file-name-nondirectory (buffer-file-name)) " --test"))) # :ide: COMPILE: Run with python3 w/o args # . (progn (save-buffer) (compile (concat "python3 ./" (file-name-nondirectory (buffer-file-name)) " "))) # :ide: COMPILE: Run with --test # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " --test"))) # :ide: COMPILE: Run w/o args # . (progn (save-buffer) (compile (concat "python ./" (file-name-nondirectory (buffer-file-name)) " "))) # :ide: +-#+ # . Compile () # # Local Variables: # mode: python # comment-start: "#" # comment-start-skip: "#+" # comment-column: 0 # truncate-lines: t # End: