Pycharm Python console synchronization


I'm using Pycharm's Python console interface to execute code from my plugin.

PyExecuteInConsole.executeCodeInConsole(prj, code, null, true, true, false, null);
Declaration in com.jetbrains.python.actions.PyExecuteInConsole.kt :

(project: Project,
commandText: String?,
editor: Editor?,
canUseExistingConsole: Boolean,
canUseDebugConsole: Boolean,
requestFocusToConsole: Boolean,
config: PythonRunConfiguration?)

How do I wait until the command is executed and the python console is idle again? The problem is, if I send another command with this function too soon - while the Python console is still busy with the previous command, the command is not executed, and I have to press ENTER in the console to run it.




Hi! Unfortunately, there's no any public API for that, unfortunately. But you can do the following:
Get the instance of currently selected console

val descriptor: RunContentDescriptor? = PyExecuteInConsole.getSelectedPythonConsole(project)

Then, for any of these consoles (or some specific one), you can do the following:

val consoleView = descriptor.executionConsole as? PythonConsoleView
val communication = consoleView.getExecuteActionHandler().getConsoleCommunication()
And console communication has a flag `communication.isExecuting()`. So you can wait until the value become `false`
Or (as an alternative) you can attach a `ConsoleCommunicationListener` to this communication and get notifications when (some) command is executed

Hi Elizabeth,


thanks for the response, I tried it but the isExecuting() never returns true... I also tried to read the text of the console with the idea - check whether the text ends with '>>>' and then you know the interpretter is idle. But I did not manage it, the PythonConsoleView.getText() only shows the non-editable part, then I tried the editor->document object of the PythonConsoleView, that always returned empty string. I wonder - how do you hook on the event that writes the '>>> ' text to the console...?


> but the isExecuting() never returns true
Hm... That's really strange. Maybe you have command queue enabled in your Python console instance (which is disabled by deafult).

For listening commands status we're using `com.jetbrains.python.console.pydev.ConsoleCommunicationListener` and prompt is updated in `com.jetbrains.python.console.PydevConsoleExecuteActionHandler#updateConsoleState`