You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Anaconda Prompt中运行Python脚本后不退出解释器?

How to Keep Python Interpreter Open After Running a Script in Anaconda Prompt

Got it, here are a few straightforward ways to keep the Python interpreter running after executing your script so you can test and use your defined functions interactively right in the Anaconda Prompt:

  • Use the -i command-line flag (simplest method)
    This is the go-to trick for most cases. Just modify your run command to include the -i flag:
    python -i filename.py
    Once your script finishes executing, Python will drop you directly into an interactive session. All functions, classes, and variables from your script will be available immediately—no need to re-import anything. For example, if your script defines a greet(name) function, you can type greet("Alice") right away to test it.

  • Add an interactive prompt directly to your script
    If you want the script to automatically launch interactive mode every time you run it (without remembering the -i flag), add this line at the end of your filename.py:
    import code; code.interact(local=globals())
    The local=globals() parameter ensures all top-level definitions from your script are accessible in the session. If your script uses an if __name__ == "__main__": block, place this line inside that block so it only triggers when you run the script directly (not when you import it as a module elsewhere).

  • Use IPython for an enhanced interactive experience
    Since you’re using Anaconda, IPython is probably already installed (it’s included in the default distribution). It offers way better features than the standard interpreter, like tab completion, syntax highlighting, and command history.
    Run your script with:
    ipython -i filename.py
    Or, if you’re already in an IPython session, execute your script with the magic command:
    %run filename.py
    Either way, you’ll stay in the IPython environment after the script runs, making it easier to iterate on your functions.

内容的提问来源于stack exchange,提问作者manofbear

火山引擎 最新活动