如何在Anaconda Prompt中运行Python脚本后不退出解释器?
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
-icommand-line flag (simplest method)
This is the go-to trick for most cases. Just modify your run command to include the-iflag: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 agreet(name)function, you can typegreet("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-iflag), add this line at the end of yourfilename.py:import code; code.interact(local=globals())
Thelocal=globals()parameter ensures all top-level definitions from your script are accessible in the session. If your script uses anif __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




