How do I create a custom python interpreter? i.e. with certain modules already included?
If you've used Ruby on Rails, I'm thinking of the feature where the user types
'rails console'
and instantly gets a Ruby console 开发者_运维知识库with rails and the current app already loaded.
I want to make something like this for a python program I'm working on, does anyone know how I would get to type say,'python myPythonConsole.py'
and open up a regular python interpreter but with my program and all its dependencies loaded?
If I understand you correctly then you might want python -i myPythonConsole.py
. It gives you a console when the script has finished so you have to run your application in a different thread.
To create a console in a script you would use the code module.
If you are using IPython (if you are not you should, it is an awesome python shell with TAB completion and many shortcuts) it is possible to set up profiles, which basically are named configurations.
Each configuration can import modules (and do other stuff) at startup.
Django does this with its "shell" command:
./manage.py shell
will open a Python shell with your Django settings loaded so you can import your project code interactively.
Source: http://code.djangoproject.com/browser/django/trunk/django/core/management/commands/shell.py
The real answer here is to use the PYTHONSTARTUP environment variable. See the tutorial section The interactive startup file.
Do your custom imports in a file interpreter.py
, and configure
PYTHONSTARTUP=/path/to/interpreter.py
Next time your start Python, the custom code will be executed before you're dropped in the REPL shell.
Here's my customization:
import os
import sys
from pathlib import Path
from pprint import pprint
pp = pprint
P = Path
version = ".".join(str(number) for number in sys.version_info[0:3])
print(f"\nCustomized Python interpreter v{version} running from {sys.prefix}")
精彩评论