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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With