PyCharm debugging with separate console
In PyCharm, debugging a Python script puts its I/O in the PyCharm console. Unfortunately, it is not a complete console, so if your script uses advanced I/O features, such as waiting for key presses or colored output, it will not work correctly.
In order to have it work, you need to run the script in a separate console window, and connect to the PyCharm debugger. This is done as follows.
First of all, create an external tool which will run the script in a dedicated console.
Name: gnome-terminal-<myprogram>
Program: gnome-terminal
Arguments: — /bin/bash -c “sleep 2; venv/bin/python3 pycharm; sleep 2”
Working Directory: $ProjectFileDir$
This runs <myprogram> with the Python executable in the venv/bin environment, in a dedicated gnome-terminal.
Then, create a new Run/debug configuration “Python Debug Server”.
Name: Remote <myprogram>
IDE host name: localhost
Port: 45257
Before launch: Add New Task -> Run external tool “gnome-terminal-<myprogram>”
At the end, in the program code add the following:
try:
if sys.argv[1] == "pycharm":
# force keeping the original stdin.
original_stdin = sys.stdin
import pydevd_pycharm
pydevd_pycharm.settrace('localhost', port=45257, suspend=False, trace_only_current_thread=False)
sys.stdin = original_stdin
sys.argv = sys.argv[0:1] + sys.argv[2:]
except IndexError:
pass
If the first argument passed to the program is “pycharm”, it will be erased and the program will connect to the debug server started by the debug configuration.