Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter Interactive Mode In Python

I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode.

In Matlab, I'd use the keyboard command to do this, but I'm not sure what the command is in python.

Is there a way to do this?

For instance:

for thing in set_of_things:     enter_interactive_mode_here()     do_stuff_to(thing) 

When enter_interactive_mode() calls, I'd like to go there, look around, and then leave and have the program continue running.

like image 415
Richard Avatar asked Nov 17 '12 17:11

Richard


People also ask

Does Python have an interactive mode?

There are two modes through which we can create and run Python scripts: 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.

How do I open Python script mode from interactive mode?

Step 1: Open the Python IDE and open the script file in Python IDE using the open option given. Or, we can even use the 'F5' button shortcut to run the script file in the Python IDE. That's how we can run or execute our Python script file using the Python IDE installed in our system.

What is interactive mode programming in Python?

Interactive Mode Script Mode. It is a way of executing a Python program in which statements are written in command prompt and result is obtained on the same. In the script mode, the Python program is written in a file. Python interpreter reads the file and then executes it and provides the desired result.


2 Answers

code.interact() seems to work somehow:

>>> import code >>> def foo(): ...     a = 10 ...     code.interact(local=locals()) ...     return a ...  >>> foo() Python 3.6.5 (default, Apr  1 2018, 05:46:30)  [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> a 10 

Ctrl+Z returns to the "main" interpreter.

You can read the locals, but modifying them doesn't seem to work this way.

like image 140
Kos Avatar answered Oct 01 '22 08:10

Kos


python -i myapp.py 

This will execute myapp.py and drop you in the interactive shell. From there you can execute functions and check their output, with the whole environment (imports, etc.) of myapp.py loaded.

For something more sophisticated - it would be better to use a debugger like pdb, setting a breakpoint. Also, most IDEs (PyDev, PyCharm, Komodo...) have graphical debuggers.

like image 22
Emil Ivanov Avatar answered Oct 01 '22 10:10

Emil Ivanov