简体   繁体   English

Python; 如何从 python 文件启动解释器?

[英]Python; how to start an interpreter from a python file?

I have a python file and within that file I want to start an interpreter within that context.我有一个 python 文件,在该文件中我想在该上下文中启动一个解释器。 Is that possible?那可能吗?

I'm currently starting an interpreter and then using exec to load in the file, but it would be quicker and easier to do it the other way around.我目前正在启动一个解释器,然后使用exec加载文件,但反过来做会更快更容易。

The use case is loading in a file full of data and helper functions that I then want to play around with in the interpreter.用例正在加载一个充满数据和辅助函数的文件,然后我想在解释器中使用它们。

The -i flag might be what you are looking for. -i标志可能是您正在寻找的。 From man python :man python

-i     When  a  script is passed as first argument or the -c option is used, enter interactive mode after executing the script or
       the command.  It does not read the $PYTHONSTARTUP file.  This can be useful to inspect global variables or a  stack  trace
       when a script raises an exception.

So for example, python -i my_script.py will run my_script.py , then leave you in an interactive session inside the same interpreter once the script completes.例如, python -i my_script.py将运行my_script.py ,然后在脚本完成后将您留在同一解释器内的交互式 session 中。

-i flag when running Python interpreter makes you stay in the interpreter after script finishes running.运行 Python 解释器时的-i标志使您在脚本完成运行后留在解释器中。

python -i file.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM