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 = new.instancemethod(function, obj, type(obj)) setattr(obj, function.__name__, m) return function return f #============================================================================== def attributesFromDict(d, self=None): if self is None: self = d.pop("self") for k, v in d.iteritems(): setattr(self, k, v) #============================================================================== def sortedDictValues(d): for k in sorted(d): yield d, d[k] #=============================================================================== def boolxor(a, b): return (a or b) and not(a and b) #=============================================================================== def getfp(fp, mode): if isinstance(fp, str) or isinstance(fp, unicode): return open(fp, mode) else: return fp #=============================================================================== def allfiles(root="./", patterns=('*',) , single_level=False , yield_folders=False): import fnmatch root = 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="./", patterns=lambda :True, single_level=False): root = 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 #============================================================================== def sign(x): if x<0:return -1 elif 0<x:return 1 else:return 0 #=============================================================================== def embedded_numbers(name): import re pieces = re.split(r"(\d+)", name) pieces[1::2] = map(int, pieces[1::2]) return tuple(pieces) #============================================================================== def exit_with_key(n=0): print("Enterキーを押すと終了します\n", file=sys.stderr) raw_input() exit(n); #============================================================================== def list_get(ls, index, default=None): index = int(index) if 0 <= index < len(ls): return ls[index] else: return default #============================================================================== def filter_dict(adict, filter): return dict(item for item in adict.iteritems() if filter(*item)) #============================================================================== 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 #============================================================================== def returns(t, f, *a, **kw): try: return [f(*a, **kw)] except t: return [] #============================================================================== def exceptional(func, alt_return=None, alt_exceptions=(Exception,), final=None, catch=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 #============================================================================== def final(func,final=None,catch=None,alt_exceptions=(),alt_return=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 #============================================================================== def remove_space(s, spaceChars=set(" \t\n\r")): #空白削除 s = unicode(s) return "".join(c for c in s if not c in spaceChars) #============================================================================== def iuniqe(seq, key=None): yielded = set() if key is None: seq, subseq = tee(seq, 2) else: seq, subseq = tee(seq, 2) subseq = imap(key, subseq) for item, k in izip(seq, subseq): if not k in yielded: yield item yielded.add(k) #============================================================================== def xproperty(fget=None, fset=None, fdel=None, doc=None): if isinstance(fget, basestring): attr_name = fget def fget(obj): return getattr(obj, attr_name) if isinstance(fset, basestring): attr_name = fset def fset(obj, val): setattr(obj, attr_name, val) return property(fget, fset, fdel, doc) #============================================================================== def trash(path , dlg=False): from win32com.shell import shell from win32com.shell.shellcon import FOF_NOCONFIRMATION, FOF_ALLOWUNDO, FOF_SILENT, FO_DELETE path = os.path.abspath(path) path = unicode(path) #区切り文字はバックスラッシュ path = path.replace("/", "\\") #\で終わっていると削除できない for i,c in enumerate(reversed(path)): if c != u"\\": if i==0: pass else: path = path[0:-i] break if not dlg: Flags = FOF_NOCONFIRMATION | FOF_ALLOWUNDO | FOF_SILENT else: Flags = FOF_NOCONFIRMATION | FOF_ALLOWUNDO# フラグ s = (0, # hwnd, FO_DELETE, #operation path, u"", Flags) shell.SHFileOperation(s) #============================================================================== def what_editor(): editor = os.getenv("VISUAL") or os.getenv("EDITOR") if not editor: if sys.platform == "windows": editor = "notepad" else: editor = "vi" return editor #============================================================================== def identity(v): return v #============================================================================== def constant(n): def f(*a, **kw): return n f.__name__ = "constant(%r)"%(n,) return f #============================================================================== class Stopwatch(object): def __init__(self, msg="", watch=True): self.watch = watch if self.watch: print(msg, end=" ") self.begin_time = 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="", enabled=True): if enabled: if msg: print(msg) begin = time.clock() yield end = time.clock() print(end - begin) else: yield #============================================================================== def import_from_string(name, code_str, default_dict = {}): """ create module from string. >>> from myutil import import_from_string >>> mod = import_from_string("foo", "def Foo():return 1") >>> type(mod) <type 'module'> >>> hasattr(mod, "Foo") True >>> callable(mod.Foo) True >>> mod.Foo() == 1 True """ import imp mod = imp.new_module(name) mod.__dict__.update(default_dict) mod_dict = mod.__dict__ mod_dict["__source__"] = code_str if "__builtins__" not in mod_dict: import __builtin__ mod_dict["__builtins__"] = __builtin__ # eval code_str in new module context. exec code_str in mod_dict return mod #============================================================================== def what_editor(): editor = os.getenv("VISUAL") or os.getenv("EDITOR") if not editor: if sys.platform == "windows": editor = "notepad" else: editor = "vi" return editor #============================================================================== class SimpleThread(threading.Thread): def __init__(self, acallable, *a, **kw): self.a = a self.kw = kw self.acallable = acallable self._result = None super(SimpleThread, self).__init__() def run(self): self._result = self.acallable(*self.a, **self.kw) def result(self): return self._result #============================================================================== def shuffled(iterable, random=random.random): """ >>> from myutil import shuffled >>> sorted(shuffled(xrange(100))) == list(xrange(100)) True """ return sorted(iterable, key=lambda x:random()) #============================================================================== def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K(object): def __init__(self, obj, *args): self.obj = 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) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K #============================================================================== def take(n, iterable): "Return first n items of the iterable as a list" return list(islice(iterable, n)) def tabulate(function, start=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=0) def nth(iterable, n, default=None): "Returns the nth item or a default value" return next(islice(iterable, n, None), default) def quantify(iterable, pred=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=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 = tee(iterable) next(b, None) return izip(a, b) def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = 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 = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [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 = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) def unique_everseen(iterable, key=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 = set() seen_add = 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 = key(element) if k not in seen: seen_add(k) yield element def unique_justseen(iterable, key=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__ == "__main__": import doctest doctest.testmod()