]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
init.py, pdbrc.py: fix flake8 warnings
[dotfiles.git] / lib / python / init.py
1 # This is startup file for interactive python.
2 # It is not automatically loaded by python interpreter.
3 # To instruct the interpreter to load it insert the following commands
4 # into your .profile (use whatever syntax and initialization file
5 # is appropriate for your shell):
6 #
7 # PYTHONSTARTUP=$HOME/init.py  # or where you really put it
8 # export PYTHONSTARTUP
9
10
11 def init():
12     import __builtin__
13     import os
14     import sys
15
16     # readline/pyreadline
17
18     pyreadlinew32_startup = os.path.join(
19         sys.prefix, 'lib', 'site-packages',
20         'pyreadline', 'configuration', 'startup.py')
21
22     if os.path.exists(pyreadlinew32_startup):
23         execfile(pyreadlinew32_startup)
24
25     else:
26         # From Bruce Edge:
27         # https://mail.python.org/pipermail/python-list/2001-March/062888.html
28
29         try:
30             import readline
31             initfile = os.environ.get('INPUTRC') \
32                 or os.path.expanduser('~/.inputrc')
33             readline.read_init_file(initfile)
34
35             histfile = os.path.expanduser('~/.python-history')
36             try:
37                 readline.read_history_file(histfile)
38             except IOError:
39                 pass  # No such file
40
41             def savehist():
42                 histfilesize = os.environ.get('HISTFILESIZE') \
43                     or os.environ.get('HISTSIZE')
44                 if histfilesize:
45                     try:
46                         histfilesize = int(histfilesize)
47                     except ValueError:
48                         pass
49                     else:
50                         readline.set_history_length(histfilesize)
51                 readline.write_history_file(histfile)
52
53             import atexit
54             atexit.register(savehist)
55
56         except (ImportError, AttributeError):
57             # no readline or atexit, or readline doesn't have
58             # {read,write}_history_file - ignore the error
59             pass
60
61     # terminal
62
63     term = os.environ.get('TERM', '')
64     if 'linux' in term:
65         background = 'dark'
66     else:
67         background = os.environ.get('BACKGROUND', 'light').lower()
68
69     # From Randall Hopper:
70     # https://mail.python.org/pipermail/python-list/2001-March/112696.html
71
72     for _term in ['linux', 'rxvt', 'screen', 'term', 'vt100']:
73         if _term not in term:
74             continue
75
76         if background == 'dark':
77             ps1_color = '3'  # yellow
78             stdout_color = '7'  # bold white
79         else:
80             ps1_color = '4'  # blue
81             stdout_color = '0'  # bold black
82
83         sys.ps1 = '\001\033[3%sm\002>>>\001\033[0m\002 ' % ps1_color
84         sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 '  # bold green
85
86         # From Denis Otkidach
87
88         class ColoredFile:
89             def __init__(self, fp, begin,
90                          end='\033[0m'):  # reset all attributes
91                 self.__fp = fp
92                 self.__begin = begin
93                 self.__end = end
94
95             def write(self, s):
96                 self.__fp.write(self.__begin+s+self.__end)
97
98             def writelines(self, lines):
99                 map(self.write, lines)
100
101             def __getattr__(self, attr):
102                 return getattr(self.__fp, attr)
103
104         sys.stdout = ColoredFile(sys.stdout, '\033[1;3%sm' % stdout_color)
105         sys.stderr = ColoredFile(sys.stderr, '\033[31m')  # red
106
107         break
108
109     try:
110         import locale
111     except ImportError:
112         pass  # locale was not compiled
113     else:
114         try:
115             locale.setlocale(locale.LC_ALL, '')
116
117             from pprint import pprint
118
119             def displayhook(value):
120                 if value is not None:
121                     __builtin__._ = value
122                     pprint(value)
123
124             sys.displayhook = displayhook
125
126         except (ImportError, locale.Error):
127             pass  # no locale support or unsupported locale
128
129     # utilities
130
131     # From: Paul Magwene:
132     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
133     # With a lot of my fixes:
134
135     class DirLister:
136         def __getitem__(self, key):
137             s = os.listdir(os.curdir)
138             return s[key]
139
140         def __getslice__(self, i, j):
141             s = os.listdir(os.curdir)
142             return s[i:j]
143
144         def __repr__(self):
145             return str(os.listdir(os.curdir))
146
147         def __call__(self, path=None):
148             if path:
149                 path = os.path.expanduser(os.path.expandvars(path))
150             else:
151                 path = os.curdir
152             return os.listdir(path)
153
154     class DirChanger:
155         def __repr__(self):
156             self()
157             return os.getcwd()
158
159         def __call__(self, path=None):
160             path = os.path.expanduser(os.path.expandvars(path or '~'))
161             os.chdir(path)
162
163     __builtin__.ls = DirLister()
164     __builtin__.cd = DirChanger()
165
166     # From Thomas Heller:
167     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
168
169     # import pdb
170     #
171     # def info(*args):
172     #    pdb.pm()
173     # sys.excepthook = info
174
175     # print working directory
176
177     class Pwd:
178         def __repr__(self):
179             return os.getcwd()
180
181         def __call__(self):
182             return repr(self)
183
184     __builtin__.pwd = Pwd()
185
186     # exit REPL with 'exit', 'quit' or simple 'x'
187
188     class _Exit:
189         def __repr__(self):
190             sys.exit()
191
192         def __call__(self, msg=None):
193             sys.exit(msg)
194
195     __builtin__.x = _Exit()
196
197     # In Python 2.5+ exit and quit are objects
198     if isinstance(__builtin__.exit, str):
199         __builtin__.exit = __builtin__.quit = x  # noqa: x is defined as _Exit
200
201     # print conten of a file
202
203     class _Cat:
204         def __repr__(self):
205             return "Usage: cat('filename')"
206
207         def __call__(self, filename):
208             fp = open(filename, 'rU')
209             text = fp.read()
210             fp.close()
211             print text
212
213     __builtin__.cat = _Cat()
214
215     # call shell
216
217     class _Sh:
218         def __repr__(self):
219             os.system(os.environ["SHELL"])
220             return ''
221
222         def __call__(self, cmdline):
223             os.system(cmdline)
224
225     __builtin__.sh = _Sh()
226
227     # paginate a file
228
229     class _Pager:
230         def __repr__(self):
231             return "Usage: pager('filename')"
232
233         def __call__(self, filename):
234             pager = os.environ.get("PAGER") or 'more'
235             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
236
237     __builtin__.pager = _Pager()
238
239     # edit a file
240
241     class _Editor:
242         def __repr__(self):
243             return "Usage: edit('filename')"
244
245         def __call__(self, filename):
246             editor = os.environ.get("VISUAL") \
247                 or os.environ.get("EDITOR") or 'vi'
248             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
249
250     __builtin__.edit = __builtin__.editor = _Editor()
251
252
253 init()
254 del init