我可以参考某种方法或资源,允许我将整个应用程序导入到python解释器中吗?
例如,当我运行python
来执行一些flask-sql查询时,我必须在每次退出时执行此操作:
python
import project
from project import app,db, etc etc
from project.models import Model, Model,
goes on and on......
如何避免这样做以绕过重复?来自Rails,只需运行rails c
并为您加载所有内容就太棒了。
答案 0 :(得分:5)
您可以通过设置环境变量PYTHONSTARTUP
:
$ cat file.py
print 'These definitions are executed before the REPL'
pi = 3.14
$ PYTHONSTARTUP=file.py python
Python 2.7.3 (default, Mar 21 2013, 07:25:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
These definitions are executed before the REPL
>>> pi
3.14
>>>
它就在python --help
的底部。
答案 1 :(得分:2)
您可以使用更好的ipython
和脚本来设置您的环境。
#!/usr/bin/env python
# appshell.py
import project
import somethingelse
import IPython
if __name__ == '__main__':
# see for notes on the arguments https://github.com/ipython/ipython/issues/8918#issuecomment-149918372
IPython.embed(module=sys.modules['__main__'], user_ns=sys.modules['__main__'].__dict__)
然后使用./appshell.py
调用它这优于PYTHONSTARTUP
,因为它可以轻松地提交到您的存储库,并且不需要配置调用环境。也就是说,你可以创建一个bash脚本来配置PYTHONSTARTUP
,然后运行python / ipython
#!/bin/bash
export PYTHONSTARTUP='...'
ipython
答案 2 :(得分:2)
我注意到了烧瓶标签......尝试使用烧瓶脚本
from flask.ext.script import Manager, Shell
from myapp import app
from mymodule import module
manager = Manager(app)
def make_shell_context():
return dict(module=module)
manager.add_command('shell', Shell(make_context=make_shell_context)),
if __name__ == "__main__":
manager.run()
./ manage.py shell将进入python shell并且mymodule已经导入
答案 3 :(得分:0)
尝试konch。从文档中:
还有一个 Flask 扩展名:flask-konch
答案 4 :(得分:0)
标准Python REPL和备用REPL(bpython
,ptython
)提供的另一个轻量级选项正在传递-i
标志:
$ cat file.py
print('These definitions are executed before the REPL')
$ python -i file.py
These definitions are executed before the REPL
>>>
$ bpython -i file.py
These definitions are executed before the REPL
bpython version 0.17.1 on top of Python 3.6.1 /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
>>>