你的Python交互启动脚本中有什么?
有没有人常用的节省时间的小技巧,可以放在Python交互式启动脚本里?我自己写了一个简单的脚本,帮助我在进行相对文件操作或者import
时知道自己在哪个目录下,使用了win32模块来改变控制台窗口的名称。
import sys
import os
import win32api
__title_prefix = 'Python %i.%i.%i %s %s' % (sys.version_info[0:4] +
(sys.version_info[4] or "",))
def __my_chdir(path):
__os_chdir(path)
win32api.SetConsoleTitle(__title_prefix + " - " + os.getcwd())
# replace chdir func
__os_chdir = os.chdir
os.chdir = __my_chdir
os.chdir(r'C:\Scripts')
3 个回答
4
这段代码的作用是……
首先,它会……然后,它会……接下来,它会……最后,它会……
通过这些步骤,我们可以看到……
总的来说,这段代码的目的是……
如果你对这些步骤有疑问,可以逐个分析,看看每一步是如何工作的。
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.
import atexit
import os
import readline
import rlcompleter
readline.parse_and_bind("tab: complete")
historyPath = os.path.expanduser("~/.history.py")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
5
我也在用see,这是一个比Python的dir更好看的替代工具。
from see import see
下面是使用see
和dir
的对比示例:
>>> k = {}
>>> dir(k)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__','__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy',
'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> see(k)
[] in < <= ==
!= > >= hash() help()
iter() len() repr() str() .clear()
.copy() .fromkeys() .get() .has_key() .items()
.iteritems() .iterkeys() .itervalues() .keys() .pop()
.popitem() .setdefault() .update() .values()