[英]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如果您使用过 Ruby on Rails,我会考虑用户键入的功能
'rails console'
'导轨控制台'
and instantly gets a Ruby console with rails and the current app already loaded.并立即获得一个带有 rails 的 Ruby 控制台,并且当前的应用程序已经加载。
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 程序做这样的事情,有谁知道我将如何打字说,
'python myPythonConsole.py'
'python myPythonConsole.py'
and open up a regular python interpreter but with my program and all its dependencies loaded?并打开一个常规的 python 解释器,但我的程序和它的所有依赖项都加载了?
If I understand you correctly then you might want python -i myPythonConsole.py
.如果我理解正确,那么您可能需要
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.如果您正在使用IPython (如果您不应该使用,它是一个很棒的 Python shell,带有 TAB 补全和许多快捷方式)可以设置配置文件,这些配置文件基本上是命名配置。
Each configuration can import modules (and do other stuff) at startup.每个配置都可以在启动时导入模块(并执行其他操作)。
Django does this with its "shell" command: Django 用它的“shell”命令来做到这一点:
./manage.py shell
will open a Python shell with your Django settings loaded so you can import your project code interactively.将打开一个加载了 Django 设置的 Python shell,以便您可以交互地导入您的项目代码。
Source: http://code.djangoproject.com/browser/django/trunk/django/core/management/commands/shell.py来源: http : //code.djangoproject.com/browser/django/trunk/django/core/management/commands/shell.py
The real answer here is to use the PYTHONSTARTUP environment variable.这里真正的答案是使用PYTHONSTARTUP环境变量。 See the tutorial section The interactive startup file .
请参阅教程部分交互式启动文件。
Do your custom imports in a file interpreter.py
, and configure在文件
interpreter.py
自定义导入,并配置
PYTHONSTARTUP=/path/to/interpreter.py
Next time your start Python, the custom code will be executed before you're dropped in the REPL shell.下次启动 Python 时,自定义代码将在您放入 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}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.