[GIS] Showing Python Console when QGIS starts

pyqgispythonqgisqgis-python-console

I wonder if there is a way to open the Python Console directly at program launch. There is a possibility to set a shortcut for the Python Console, but I can't find such an option for the QGIS program launch.

Best Answer

Using macros

You can start QGIS Python console when opening a project by writing a couple of lines in QGIS->Project->Project Properties:

def openProject():
    import qgis     
    qgis.utils.iface.actionShowPythonDialog().trigger()

Make sure you enable macros on your project, this way: Settings->Options->General->Enable macros: Always


Using startup.py

As you want the QGIS Python console to open when launching QGIS, you can create (if it doesn't exist already) a startup.py file in %APPDATA%\QGIS\QGIS3\ (e.g., GNU/Linux: /home/USER/.local/share/QGIS/QGIS3/ or Windows: C:\Users\USER\AppData\Roaming\QGIS\QGIS3\) and write:

import qgis     
qgis.utils.iface.actionShowPythonDialog().trigger()

EDIT (to address a follow-up question by @Miro)

As pointed out by Miro, if QGIS Python Console is open, qgis.utils.iface.actionShowPythonDialog().trigger() will close it, so, if we are writing a QGIS plugin, it might make sense to know if the Python Console is open (visible) or not.

You can know if the Python Console is not visible (and then open it) by running this code:

from qgis.PyQt.QtWidgets import QDockWidget
pythonConsole = iface.mainWindow().findChild(QDockWidget, 'PythonConsole')
if not pythonConsole or not pythonConsole.isVisible():
    from qgis.utils import iface
    iface.actionShowPythonDialog().trigger()