2

I want to export the messages that appear on the Console Python (for example this below) using a script:

enter image description here

But I can't find a way to store it in a txt file. Any suggestion?

Taras
  • 32,823
  • 4
  • 66
  • 137
freecma80
  • 103
  • 5

1 Answers1

1

This is a really horrible way of finding the right widget, I can almost guarantee there is a more elegant way (suggestions welcome), but nonetheless:

cons = iface.mainWindow().findChild(QDockWidget, 'PythonConsole')

children = cons.children()

pc = children[-1] # console.console.PythonConsole

pcw = pc.children()[0] # console.console.PythonConsoleWidget

shell = pcw.shellOutWidget

scin = shell.children()[1] # console.console_output.ShellOutputScintilla

contents = scin.text() # console text

write log to file

with open('console_log.txt', 'w+') as logfile: logfile.write(contents)

Matt
  • 16,843
  • 3
  • 21
  • 52
  • Nice code, however, I am getting the following error: "AttributeError: 'QSplitter' object has no attribute 'shellOutWidget'" – Taras Dec 09 '23 at 08:52
  • The weirdest child is this one console.console.PythonConsoleWidge ^_^ – Taras Dec 09 '23 at 09:09
  • In that case, it's probably better to find the child using if isinstance() rather than by indexing. I thought that might causes issues... – Matt Dec 09 '23 at 09:20
  • And indeed. It took quite some digging to find my way through the hierarchy :) – Matt Dec 09 '23 at 09:34
  • At least we know where to look for: https://gis.stackexchange.com/questions/132695/showing-python-console-when-qgis-starts @_@ – Taras Dec 09 '23 at 09:38