[QGIS-Developer] Multiple python scripts in python console?

Raymond Nijssen r.nijssen at terglobo.nl
Fri May 5 05:24:47 PDT 2023


Hi Klaus,

Thank you so much, it works!!

Replying to you and the dev list, hoping this solution will end up in 
the same thread.

Kind regards,

Raymond


On 05-05-2023 12:52, Klaus Affeldt wrote:
> Hi Raymond,
> 
> can't write to the list yet, so i answer you directly:
> 
> The python console has a different working directory then the called script.
> You have to find out the path of the script and append it to the python search path.
> 
> 
> # script_1.py
> 
> import os
> from console.console import _console
> 
> # name and path of this script
> script_path = _console.console.tabEditorWidget.currentWidget().path
> 
> # only the path
> path=(os.path.dirname(script_path))+"/"
> print (path)
> 
> # append python search path
> import sys
> sys.path.append(path)
> 
> from script_2 import TestClass
> 
> obj1 = TestClass('Ray')
> print(obj1)
> 
> 
> # to dynamicly reload changes on script_2.py
> import imp
> 
> import script_2
> 
> imp.reload(script_2)
> obj1 = script_2.TestClass('Ray')
> print(obj1)
> 
> 
> 
> Mit freundlichen Grüßen
> 
> Ihre PV ANSPERGER mbH
> 
> Klaus Affeldt
> 
> Zentrale Kamp-Lintfort
> Südstraße 25
> 47475 Kamp-Lintfort
> Tel. +49 2842 9635-14
> Fax: +49 2842 9635-99
> https://www.ansperger.de
> 
> 
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> 
> Hi developers,
> 
> While writing a python script in the QGIS python console editor I needed
> to write a new class and for convenience I put that in its own python file.
> 
> Both files are in the same directory, but I cannot import my class in
> the other script.
> 
> Here's an example:
> 
> 
> # script_1.py
> 
> from .script_2 import TestClass
> obj1 = TestClass('Ray')
> print(obj1)
> 
> 
> 
> 
> # script_2.py:
> 
> class TestClass():
> 
>       def __init__(self, name):
>           self.name = name
> 
>       def __str__(self):
>           return f'TestClass[{self.name}]'
> 
> 
> 
> It all works properly if I put my class definition in script_1 but as
> the code is growing (and a customer of mine needs to understand this
> too) it would really be nice to split the code over multiple files.
> Is there a way? Or another approach?
> 
> Kind regards,
> Raymond


More information about the QGIS-Developer mailing list