This repository has been archived by the owner on Oct 10, 2023. It is now read-only.
forked from jezdez/python-startup
/
startup.py
391 lines (340 loc) · 10.9 KB
/
startup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""
My Python startup file, carefully gathered from different sources (see below)
Get code from Github::
git clone https://github.com/jezdez/python-startup.git ~/.python
Put this in your shell profile::
export PYTHONSTARTUP=$HOME/.python/startup.py
In case you haven't saved these files in $HOME/.python make sure to set
PYTHONUSERDIR approppriately, too::
export PYTHONUSERDIR=/path/to/dir
"""
# python-startup.py
# Author: Nathan Gray, based on interactive.py by Robin Friedrich and an
# evil innate desire to customize things.
# E-Mail: n8gray@caltech.edu
#
# Version: 0.6
# These modules are always nice to have in the namespace
############################################################################
# Below this is Robin Friedrich's interactive.py with some edits to decrease
# namespace pollution and change the help functionality
# NG
#
# Also enhanced 'which' to return filename/lineno
# Patch from Stephan Fiedler to allow multiple args to ls variants
# NG 10/21/01 -- Corrected a bug in _glob
#
########################### interactive.py ###########################
# """Functions for doing shellish things in Python interactive mode.
#
# Meant to be imported at startup via environment:
# setenv PYTHONSTARTUP $HOME/easy.py
# or
# export PYTHONSTARTUP=$HOME/easy.py
#
# - Robin Friedrich
# """
import functools
import glob
import os
import shutil
import subprocess
import sys
import time
import types
try:
from pydoc import help
except ImportError:
def help(*objects):
"""Print doc strings for object(s).
Usage: >>> help(object, [obj2, objN]) (brackets mean [optional] argument)
"""
if len(objects) == 0:
help(help)
return
for obj in objects:
try:
print('****', obj.__name__ , '****')
print(obj.__doc__)
except AttributeError:
print(obj, 'has no __doc__ attribute')
print()
try:
from collections import defaultdict
except ImportError:
pass
try:
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
from django.db.models.loading import get_models
except ImportError:
pass
else:
for m in get_models():
exec("from %s import %s" % (m.__module__, m.__name__))
home = os.path.expandvars('$HOME')
user_dir = os.environ.get("PYTHONUSERDIR")
sys.path.append(user_dir)
##### Some settings you may want to change #####
# Define the editor used by the edit() function. Try to use the editor
# defined in the Unix environment, or default to vi if not set.
# (patch due to Stephan Fiedler)
#
# %(lineno)s gets replaced by the line number. Ditto %(fname)s the filename
EDITOR = os.environ.get('EDITOR', 'emacs')
editorbase = EDITOR.split()[0]
if editorbase in ['nedit', 'nc', 'ncl', 'emacs', 'emacsclient', 'xemacs'] :
# We know these editors supoprt a linenumber argument
EDITOR = EDITOR + ' +%(lineno)s %(fname)s &'
elif editorbase in ['vi', 'vim', 'jed']:
# Don't want to run vi in the background!
# If your editor requires a terminal (e.g. joe) use this as a template
EDITOR = 'gnome-terminal -e \'' + EDITOR + ' +%(lineno)s %(fname)s\' &'
else:
# Guess that the editor only supports the filename
EDITOR = EDITOR + ' %(fname)s &'
del editorbase
# The place to store your command history between sessions
histfile = os.path.expanduser('~/.python_history')
##### Now set up the interactive features that I like #####
# Colorize the prompts if possible (This is probably non-portable muck)
# Thanks to Stephan Fiedler for the fix!
if os.environ[ 'TERM' ] in [ 'xterm', 'vt100' ]:
pre = chr(1) + "\033[1;32m" + chr(2) # Turn the text green
suf = chr(1) + "\033[0m" + chr(2) # Reset to normal
sys.ps1 = pre + ">>>" + suf + " "
sys.ps2 = pre + "..." + suf + " "
del pre, suf
try:
# Set up colorized tracebacks
# Make sure to do this *before* installing LazyPython
import ultraTB
sys.excepthook = ultraTB.ColorTB()
except ImportError:
pass
# LazyPython only works for Python versions 2.1 and above
try:
# Try to use LazyPython
from LazyPython import LazyPython
sys.excepthook = LazyPython()
except ImportError:
pass
# Pretty-print at the command prompt for more readable dicts and lists.
try:
import __builtin__
except ImportError:
import builtins
__builtin__ = builtins
from pprint import pprint
def myhook(value, show=pprint, bltin=__builtin__):
if value is not None:
bltin._ = value
show(value)
sys.displayhook = myhook
try:
# Try to set up command history completion/saving/reloading
import readline, atexit, rlcompleter
readline.parse_and_bind('tab: complete')
try:
readline.read_history_file(histfile)
except IOError:
pass # It doesn't exist yet.
def savehist():
try:
global histfile
import readline
readline.write_history_file(histfile)
except:
print('Unable to save Python command history')
atexit.register(savehist)
del atexit
except ImportError:
pass
##### Make reload work recursively #####
try:
import __builtin__, deep_reload
__builtin__.reload = deep_reload.reload
del __builtin__, deep_reload
except ImportError:
pass
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print("%s time: %.5f" % (func.__name__, end - start))
return res
return wrapper
def reimport(mod, locals=None):
if isinstance(mod, str):
modname = mod
else:
modname = mod.__name__
sys.modules[modname] = None
del sys.modules[modname]
new_mod = __import__(modname)
if locals is not None:
locals[modname] = new_mod
return new_mod
def _glob(filenames):
"""Expand a filename or sequence of filenames with possible
shell metacharacters to a list of valid filenames.
Ex: _glob(('*.py*',)) == ['able.py','baker.py','charlie.py']
"""
if type(filenames) is types.StringType:
return glob.glob(filenames)
flist = []
for filename in filenames:
globbed = glob.glob(filename)
if globbed:
for file in globbed:
flist.append(file)
else:
flist.append(filename)
return flist
def _expandpath(d):
"""Convert a relative path to an absolute path.
"""
return os.path.join(os.getcwd(), os.path.expandvars(d))
def _ls(options, *files):
"""
_ls(options, ['fname', ...'])
Lists the given filenames, or the current directory if none are
given, with the given options, which should be a string like '-lF'.
"""
if len(files) == 0 :
args = os.curdir
else :
args = ' '.join(files)
subprocess.Popen('ls %s %s' % (options, args), shell=True)
def ls(*files):
"""Same as 'ls -aF'
Usage: >>> ls(['dirname', ...]) (brackets mean [optional]
argument)
"""
_ls('-aF', *files)
def ll(*files):
"""Same as 'ls -alF'
Usage: >>> ll(['dirname', ...]) (brackets mean [optional]
argument)
"""
_ls('-alF', *files)
def lr(*files):
"""Recursive listing. same as 'ls -aRF'
Usage: >>> lr(['dirname', ...]) (brackets mean [optional]
argument)
"""
_ls('-aRF', *files)
mkdir = os.mkdir
def rm(*args):
"""Delete a file or files.
Usage: >>> rm('file.c' [, 'file.h']) (brackets mean [optional] argument)
Alias: delete
"""
filenames = _glob(args)
for item in filenames:
try:
os.remove(item)
except os.error as detail:
print("%s: %s" % (detail[1], item))
delete = rm
def rmdir(directory):
"""Remove a directory.
Usage: >>> rmdir('dirname')
If the directory isn't empty, can recursively delete all sub-files.
"""
try:
os.rmdir(directory)
except os.error:
#directory wasn't empty
answer = raw_input(directory+" isn't empty. Delete anyway?[n] ")
if answer and answer[0] in 'Yy':
subprocess.Popen('rm -rf %s' % directory, shell=True)
print(directory + ' Deleted.')
else:
print(directory + ' Unharmed.')
def mv(*args):
"""Move files within a filesystem.
Usage: >>> mv('file1', ['fileN',] 'fileordir')
If two arguments - both must be files
If more arguments - last argument must be a directory
"""
filenames = _glob(args)
nfilenames = len(filenames)
if nfilenames < 2:
print('Need at least two arguments')
elif nfilenames == 2:
try:
os.rename(filenames[0], filenames[1])
except os.error as detail:
print("%s: %s" % (detail[1], filenames[1]))
else:
for filename in filenames[:-1]:
try:
dest = filenames[-1]+'/'+filename
if not os.path.isdir(filenames[-1]):
print('Last argument needs to be a directory')
return
os.rename(filename, dest)
except os.error as detail:
print("%s: %s" % (detail[1], filename))
def cp(*args):
"""Copy files along with their mode bits.
Usage: >>> cp('file1', ['fileN',] 'fileordir')
If two arguments - both must be files
If more arguments - last argument must be a directory
"""
filenames = _glob(args)
nfilenames = len(filenames)
if nfilenames < 2:
print('Need at least two arguments')
elif nfilenames == 2:
try:
shutil.copy(filenames[0], filenames[1])
except os.error as detail:
print("%s: %s" % (detail[1], filenames[1]))
else:
for filename in filenames[:-1]:
try:
dest = filenames[-1]+'/'+filename
if not os.path.isdir(filenames[-1]):
print('Last argument needs to be a directory')
return
shutil.copy(filename, dest)
except os.error as detail:
print("%s: %s" % (detail[1], filename))
def cpr(src, dst):
"""Recursively copy a directory tree to a new location
Usage: >>> cpr('directory0', 'newdirectory')
Symbolic links are copied as links not source files.
"""
shutil.copytree(src, dst)
def ln(src, dst):
"""Create a symbolic link.
Usage: >>> ln('existingfile', 'newlink')
"""
os.symlink(src, dst)
def lnh(src, dst):
"""Create a hard file system link.
Usage: >>> ln('existingfile', 'newlink')
"""
os.link(src, dst)
def pwd():
"""Print current working directory path.
Usage: >>> pwd()
"""
print(os.getcwd())
def env():
"""List environment variables.
Usage: >>> env()
"""
#unfortunately environ is an instance not a dictionary
envdict = {}
for key, value in os.environ.items():
envdict[key] = value
pprint(envdict)
try:
import __builtin__
except ImportError:
import builtins
__builtin__ = builtins