Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you programmatically tell the CPython interpreter to enter interactive mode when done?

Tags:

python

cpython

If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.

like image 840
Nick Avatar asked Feb 26 '09 17:02

Nick


People also ask

How do you go into interactive mode in Python?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.

How will you execute Python instructions in interactive mode and script mode?

The interactive mode involves running your codes directly on the Python shell which can be accessed from the terminal of the operating system. In the script mode, you have to create a file, give it a name with a . py the extension then runs your code. The interactive mode is suitable when running a few lines of code.

How do I run code in interactive mode?

In order to run our program in the interactive mode, we can use command prompt in windows, terminal in Linux, and macOS. Let us see understand the execution of python code in the command prompt with the help of an example: Example 1: To run python in command prompt type “python”.

What is script and interactive mode in Python?

Answer: Interactive mode is where you type commands and they are immediately executed. Script mode is where you put a bunch of commands into a file (a script), and then tell Python to run the file.


2 Answers

You want the code module.

#!/usr/bin/env python

import code    
code.interact("Enter Here")
like image 101
Douglas Leeder Avatar answered Sep 19 '22 04:09

Douglas Leeder


Set the PYTHONINSPECT environment variable. This can also be done in the script itself:

import os
os.environ["PYTHONINSPECT"] = "1"

For debugging unexpected exceptions, you could also use this nice recipe http://code.activestate.com/recipes/65287/

like image 33
theller Avatar answered Sep 23 '22 04:09

theller