Windows上のPythonインタラクティブシェルでタブ補完する



WindowsでPython2.6のインタラクティブモードでタブ補完をしたい場合に使うバッチ - 試行錯誤と創意工夫(S!アプリ開発日記+α)

によると、PYTHONSTARTUPに適当に追加すればよいそうです。


PYTHONSTARTUP環境変数に指定されたスクリプトは、

インタラクティブシェル起動時に実行されるので、


よく使うモジュールをimportするなど書いておきます。



sysとか、osとか、pprintとか、functoolsとか。functoolsは違うか(笑)。


以下、私のPYTHONSTARTUPをさらして置きます。



ちなみに%HOME%\_pythonrc.py
という名前です。

#encoding:utf-8
from __future__ import (
    with_statement,
    division,
    print_function,
)
import rlcompleter
rlcompleter.readline.parse_and_bind('tab: complete')

from myutil import *
from see import see



sysやosのimportはmyutilの中でやっています。


Pythonクックブックなどのコードで、使用頻度が高そうなものを、
チョコチョコ書いたものです。
今見返すとほとんど使わないのもありますが。


多分、Python使いは、それぞれにこういうモジュールを持ってるんですよね?

#encoding:shift-jis
"""
miscellaneous utility module
please write in top of your scripy to use this module

from myutil import *
"""
from __future__ import (
    division, 
    with_statement, 
    print_function
)

import sys
import os
import shutil
import itertools
import functools
from itertools import *
from functools import *
import math
import re
import random
from pprint import *
from collections import *
import copy
import time
import operator
from operator import *
import string
import types
import threading
from contextlib import contextmanager 
import codecs


#===============================================================================

class Bunch(object):
    def __init__(self, **kw):
        self.__dict__.update(kw)
    
    def __str__(self):
        return "Bunch(%s)"%(self.__dict__)
        
    def __repr__(self):
        return "%s(%r)"%(object.__repr__(self), vars(self))
    
    def _asdict(self):
        return vars(self)
    
#==============================================================================

class Holder(object):
    def __init__(self, value=None):
        self.value = value
    
    def get(self):
        return self.value
    
    def set(self, value):
        self.value = value
        return self.value

#==============================================================================

class Null(object):
    def __init__(self, *a, **kw):pass
    def __call__(self, *a, **kw):return self
    def __nonzero__(self):return 1
    def __getattr__(self, name): return self
    def __setattr__(self, name, value):pass
    def __delattr__(self, name):pass

#==============================================================================

import new
def singletonmethod(obj):
    """
    >>> from singletonmethod import singletonmethod
    >>> class A(object):pass
    >>> a = A()
    >>> @singletonmethod(a)
    ... def hello(self):
    ...     print "hello world!"
    >>> a.hello()
    hello world!
    >>> type(a.hello)
    <type 'instancemethod'>
    """
    def f(function):
        m &#061; new.instancemethod(function, obj, type(obj)) 
        setattr(obj, function.__name__, m)
        return function
    return f

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def attributesFromDict(d, self&#061;None):
    if self is None:
        self &#061; d.pop("self")
    
    for k, v in d.iteritems():
        setattr(self, k, v)

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def sortedDictValues(d):
    for k in sorted(d):
        yield d, d[k]
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def boolxor(a, b):
    return (a or b) and not(a and b)

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def getfp(fp, mode):
    if isinstance(fp, str) or isinstance(fp, unicode):
        return open(fp, mode)
    else:
        return fp
        
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def allfiles(root&#061;"./", patterns&#061;('*',) , single_level&#061;False , yield_folders&#061;False):
    import fnmatch
    
    root &#061; os.path.abspath(unicode(root))
    for path, subdirs, files in os.walk(root):
        if yield_folders:
            files.extend(subdirs)
        
        for name in files:
            if any(fnmatch.fnmatch(name, p) for p in patterns):
                yield os.path.abspath(os.path.join(path, name))
            
        if single_level:
            break


def alldirs(root&#061;"./", patterns&#061;lambda :True, single_level&#061;False):
    root &#061; os.path.abspath(unicode(root))
    for path, subdirs, files in os.walk(root):
        for dir in subdirs:
            yield os.path.abspath(os.path.join(path, dir))

        if single_level:
            break

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def sign(x):
    if x<0:return -1
    elif 0<x:return 1
    else:return 0
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def embedded_numbers(name):
    import re
    pieces &#061; re.split(r"(\d+)", name)
    pieces[1::2] &#061; map(int, pieces[1::2])
    return tuple(pieces)

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def exit_with_key(n&#061;0):
    print("Enterキーを押すと終了します\n", file&#061;sys.stderr)
    raw_input()
    exit(n);

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def list_get(ls, index, default&#061;None):
    index &#061; int(index)
    if 0 <&#061; index < len(ls):
        return ls[index]
    else:
        return default

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def filter_dict(adict, filter):
    return dict(item for item in adict.iteritems() if filter(*item))
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def throws(t, f, *a, **kw):
    """
    >>> from myutil import throws
    >>> throws(ValueError, int, "xyz")
    True
    >>> throws(ValueError, int, "1")
    False
    """
    try:
        f(*a, **kw)
    except t:
        return True
    else:
        return False

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def returns(t, f, *a, **kw):
    try:
        return [f(*a, **kw)]
    except t:
        return []

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def exceptional(func, alt_return&#061;None, alt_exceptions&#061;(Exception,), final&#061;None, catch&#061;None):
    """turns exceptions into alternative return value"""
    def _exceptional(*args,**kwargs):
        try:
            try: return func(*args,**kwargs)
            except alt_exceptions:
                return alt_return
            except:
                if catch: return catch(sys.exc_info(), lambda:func(*args,**kwargs))
                raise
        finally:
            if final: final()
    return _exceptional

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def final(func,final&#061;None,catch&#061;None,alt_exceptions&#061;(),alt_return&#061;None):
    """connects a final call to a function call"""
    def _exceptional(*args,**kwargs):
        try:
            try: return func(*args,**kwargs)
            except alt_exceptions:
                return alt_return
            except:
                if catch: return catch(sys.exc_info(), lambda:func(*args,**kwargs))
                raise
        finally:
            if final: final()
    return _exceptional
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def remove_space(s, spaceChars&#061;set(" \t\n\r")):
    #空白削除
    s &#061; unicode(s)
    return "".join(c for c in s if not c in spaceChars)

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def iuniqe(seq, key&#061;None):
    yielded &#061; set()
    if key is None:
        seq, subseq &#061; tee(seq, 2)
    else:
        seq, subseq &#061; tee(seq, 2)
        subseq &#061; imap(key, subseq)
    
    for item, k in izip(seq, subseq):
        if not k in yielded:
            yield item
            yielded.add(k)
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def xproperty(fget&#061;None, fset&#061;None, fdel&#061;None, doc&#061;None):
    if isinstance(fget, basestring):
        attr_name &#061; fget
        def fget(obj):
            return getattr(obj, attr_name)
    
    if isinstance(fset, basestring):
        attr_name &#061; fset
        def fset(obj, val):
            setattr(obj, attr_name, val)
    
    return property(fget, fset, fdel, doc)

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def trash(path , dlg&#061;False):
    from win32com.shell import shell
    from win32com.shell.shellcon import FOF_NOCONFIRMATION, FOF_ALLOWUNDO, FOF_SILENT, FO_DELETE
    
    path &#061; os.path.abspath(path)
    path &#061; unicode(path)
    #区切り文字はバックスラッシュ
    path &#061; path.replace("/", "\\")
    
    #\で終わっていると削除できない
    for i,c in enumerate(reversed(path)):
        if c !&#061; u"\\":
            if i&#061;&#061;0:
                pass
            else:
                path &#061; path[0:-i]
            break
    if not dlg:
        Flags &#061; FOF_NOCONFIRMATION | FOF_ALLOWUNDO | FOF_SILENT
    else:
        Flags &#061; FOF_NOCONFIRMATION | FOF_ALLOWUNDO# フラグ
    
    s &#061; (0, # hwnd,
         FO_DELETE, #operation
         path,
         u"",
         Flags)
    shell.SHFileOperation(s)

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def what_editor():
    editor &#061; os.getenv("VISUAL") or os.getenv("EDITOR")
    if not editor:
        if sys.platform &#061;&#061; "windows":
            editor &#061; "notepad"
        else:
            editor &#061; "vi"
    return editor

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def identity(v):
    return v

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def constant(n):
    def f(*a, **kw):
        return n
    f.__name__ &#061; "constant(%r)"%(n,)
    return f
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

class Stopwatch(object):
    def __init__(self, msg&#061;"", watch&#061;True):
        self.watch &#061; watch
        if self.watch:
            print(msg, end&#061;" ")
        self.begin_time &#061; time.clock()
    
    def stop(self):
        if self.watch:
            print(time.clock() - self.begin_time)
    
    def __exit__( self, exc_type, exc_value, traceback):
        self.stop()
    
    def __enter__( self):
        pass

@contextmanager
def stopwatch(msg&#061;"", enabled&#061;True):
    if enabled:
        if msg:
            print(msg)
        
        begin &#061; time.clock()
        yield
        end &#061; time.clock()
        
        print(end - begin)
    else:
        yield
    
#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def import_from_string(name, code_str,  default_dict &#061; {}):
    """
        create module from string.
        
        >>> from myutil import import_from_string
        >>> mod &#061; import_from_string("foo", "def Foo():return 1")
        >>> type(mod)
        <type 'module'>
        >>> hasattr(mod, "Foo")
        True
        >>> callable(mod.Foo)
        True
        >>> mod.Foo() &#061;&#061; 1
        True
    """
    import imp
    mod &#061; imp.new_module(name)
    
    mod.__dict__.update(default_dict)
    mod_dict &#061; mod.__dict__
    mod_dict["__source__"] &#061; code_str
    
    if "__builtins__" not in mod_dict:
        import __builtin__
        mod_dict["__builtins__"] &#061; __builtin__
    
    # eval code_str in new  module context.
    exec code_str in mod_dict
    
    return mod

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def what_editor():
    editor &#061; os.getenv("VISUAL") or os.getenv("EDITOR")
    if not editor:
        if sys.platform &#061;&#061; "windows":
            editor &#061; "notepad"
        else:
            editor &#061; "vi"
    return editor

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

class SimpleThread(threading.Thread):
    def __init__(self, acallable, *a, **kw):
        self.a &#061; a
        self.kw &#061; kw
        self.acallable &#061; acallable
        self._result &#061; None
        super(SimpleThread, self).__init__()
    
    def run(self):
        self._result &#061; self.acallable(*self.a, **self.kw)
    
    def result(self):
        return self._result

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def shuffled(iterable, random&#061;random.random):
    """
    >>> from myutil import shuffled
    >>> sorted(shuffled(xrange(100))) &#061;&#061; list(xrange(100))
    True
    """
    return sorted(iterable, key&#061;lambda x:random())

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def cmp_to_key(mycmp):
    'Convert a cmp&#061; function into a key&#061; function'
    class K(object):
        def __init__(self, obj, *args):
            self.obj &#061; obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) &#061;&#061; 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <&#061; 0  
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >&#061; 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) !&#061; 0
    return K

#&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;&#061;

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

def tabulate(function, start&#061;0):
    "Return function(0), function(1), ..."
    return imap(function, count(start))

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    collections.deque(islice(iterator, n), maxlen&#061;0)

def nth(iterable, n, default&#061;None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

def quantify(iterable, pred&#061;bool):
    "Count how many times the predicate is true"
    return sum(imap(pred, iterable))

def padnone(iterable):
    """Returns the sequence elements and then returns None indefinitely.

    Useful for emulating the behavior of the built-in map() function.
    """
    return chain(iterable, repeat(None))

def ncycles(iterable, n):
    "Returns the sequence elements n times"
    return chain.from_iterable(repeat(iterable, n))

def dotproduct(vec1, vec2):
    return sum(imap(operator.mul, vec1, vec2))

def flatten(listOfLists):
    return list(chain.from_iterable(listOfLists))

def repeatfunc(func, times&#061;None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b &#061; tee(iterable)
    next(b, None)
    return izip(a, b)

def grouper(n, iterable, fillvalue&#061;None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args &#061; [iter(iterable)] * n
    return izip_longest(fillvalue&#061;fillvalue, *args)

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending &#061; len(iterables)
    nexts &#061; cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -&#061; 1
            nexts &#061; cycle(islice(nexts, pending))

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s &#061; list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def compress(data, selectors):
    "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
    return (d for d, s in izip(data, selectors) if s)

def combinations_with_replacement(iterable, r):
    "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
    # number items returned:  (n+r-1)! / r! / (n-1)!
    pool &#061; tuple(iterable)
    n &#061; len(pool)
    if not n and r:
        return
    indices &#061; [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] !&#061; n - 1:
                break
        else:
            return
        indices[i:] &#061; [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s &#061; list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def unique_everseen(iterable, key&#061;None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen &#061; set()
    seen_add &#061; seen.add
    if key is None:
        for element in iterable:
            if element not in seen:
                seen_add(element)
                yield element
    else:
        for element in iterable:
            k &#061; key(element)
            if k not in seen:
                seen_add(k)
                yield element

def unique_justseen(iterable, key&#061;None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return imap(next, imap(itemgetter(1), groupby(iterable, key)))
    
if __name__ &#061;&#061; "__main__":
    import doctest
    doctest.testmod()