agisoft-llc / metashape-scripts

Python scripts for Metashape (former PhotoScan)
MIT License
385 stars 206 forks source link

How to handle import libraries without repeats #17

Closed ahalota closed 4 years ago

ahalota commented 4 years ago

I'm running into an issue while testing creating a script similar to those posted here (with the GUI add-ons).

If I import a library (usually one with my utility functions) in my script that is loaded, notice an issue in my code, and then run the script again (creating a second entry in the menu bar, but it's ok for testing), it loads the imported library again as well. This seems to create a mess if I do it a few times in a row with things overwriting each other in a weird manner, but I can't figure out how to stop it.

Right now my code is messy with everything in the single script file to avoid this, but I'd like to know how to compartmentalize it while still being able to test it in the GUI without reopening Metashape each time.

Any suggestions?

PolarNick239 commented 4 years ago

This seems to create a mess if I do it a few times in a row with things overwriting each other in a weird manner, but I can't figure out how to stop it.

Can you please illustrate what's going wrong? Maybe you have simple reproducer with library and final script with steps to reproduce 'overwriting in a weird manner'?

After script editing I am also just running script again and then clicking on the last entry in the menu bar and I don't remember to encounter overwriting behavior.

PolarNick239 commented 4 years ago

Please feel free to reopen issue if you still have the problem.

ahalota commented 4 years ago

Ok, I remembered now the exact issue.

If I am trying to make a sub-module that I import in my script, such as "metashape_util.py" which gets loaded into my various "tool1.py" , etc. via:

import metashape_util

And then I make edits to "metashape_util.py", they are not recognized, even if I reload the script. So, basically the GUI console script loader recognizes changes to my main code, but it does not make any updates to the libraries that are imported.

PolarNick239 commented 4 years ago

It seems that I reproduced similar behaviour.

Let's suppose I have utils.py:

def foo():
    print(10)

And I am executing the following script script.py:

import utils
utils.foo()

I will, of course, see "10" printed in console. Then, if I will change a constant to a new value in utils.py and execute script.py once more - I will again see "10" in console instead of the new value.

This is a python-related problem and it can be solved like it can be solved for any Python interpreter with reloading module - see script.py with workaround:

import utils

import importlib
importlib.reload(utils)

utils.foo()