12

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.

2
  • There is a way to write a file that gets executed when QGIS starts, which can be helpful for customized settings like these. The question is whether you can open the console programmaticaly or not. Do you know if you can do that? Commented Feb 2, 2015 at 11:00
  • I've searched in the API but the only class that is related to python is the QgsPythonRunner, wich is not the console.
    – Martin
    Commented Feb 2, 2015 at 11:21

1 Answer 1

16

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()
4
  • Is there a way to check if console is already open? Because if it is the trigger() is going to close it.
    – Miro
    Commented Sep 30, 2016 at 5:16
  • @Miro, there is a way! I've edited my answer with instructions. Commented Oct 2, 2016 at 12:52
  • 1
    In 2.18, the project macro works but the startup script fails to open the console.
    – underdark
    Commented Nov 22, 2016 at 19:58
  • For the startup script to work properly, I needed to add the code snippet into a SLOT, and connect it to iface.initializationCompleted() SIGNAL. Commented Jun 6, 2020 at 3:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.