我找到了一種方法如果你使用的是django-extensions-shell_plus,那麼這個方法就行得通。這有點不好意思,但通過這種方式,您的啓動文件會自動加載,並且您不必在ipython會話開始時輸入任何運行命令。
因此,我編輯了django_extensions目錄中的文件shells.py
,這在我的情況下位於/usr/local/lib/python2.7/dist-packages/django_extensions/management/shells.py
。我在函數import_objects(options, style):
中添加了這些行,因此它會導入由環境參數PYTHONSTARTUP
定義的文件startup.py
的內容。
def import_objects(options, style):
# (...)
import os, sys, pkgutil
if 'PYTHONSTARTUP' in os.environ:
try:
sys.path.append(os.environ['PYTHONSTARTUP'])
import startup
content = [element for element in dir(startup) if not element.startswith('__')]
for element in content:
imported_objects[element] = getattr(startup, element)
except Exception, ex:
sys.exit("Could not import startup module content, Error:\n%s" % ex)
現在,當我啓動shell_plus-shell時,我將其環境變量賦予啓動python腳本。我的bash腳本與一切啓動外殼到位看起來是這樣的:
#!/bin/bash
export PYTHONSTARTUP=/home/ifischer/src/myproject/startup.py # tells shell_plus to load this file
python /home/ifischer/src/myproject/manage.py shell_plus --ipython
現在我有機會從IPython的會話的開始startup.py定義的所有方法和變量。
因此,您可以重複使用併爲每個項目定製啓動文件,預加載不同方面。
也許有一個更清晰的方式來包含我添加到shells.py的行?但是現在這種方法對我來說工作得很好。
'manage.py shell'也是如此,啓動文件不會被執行。希望他們能很快解決這個問題。 (ps,v 0.13) – Paolo 2012-07-12 20:28:30