1

I have a script for which I want something ("This is the script version 1.0" in the example below) to be printed only when imported (or reloaded). Basically, my script has several functions and one class, but somehow (since I upgraded to python 3.8 actually), the first message in the code is printed several time while executing functions in the class. So is there a way to check when I first import the module? The script is basically like this:

import numpy as np

print('This is the script version 1.0')

def func1():
   blah blah

def func2():
   blah blah

class Open:
   def __init__(self, others):
      blah blah

   def func3(self)
      blah blah

def func4():
   blah blah

def func5():
   blah blah

  • 1
    How are you using this script? I would expect the module to be cached and only ever executed once. – Carcigenicate Aug 24 '21 at 17:09
  • Are you using any multiprocessing and have not done an `if __name__ == '__main__':` see also: https://stackoverflow.com/questions/419163/what-does-if-name-main-do – JonSG Aug 24 '21 at 17:36
  • I use a terminal, open ipython and then import the module. I indeed use multiprocessing. I am not using ```if __name__ == '__main__':``` – user3177899 Aug 24 '21 at 17:42
  • Check out : https://stackoverflow.com/questions/42602584/how-to-use-multiprocessing-pool-in-an-imported-module – JonSG Aug 24 '21 at 18:22
  • The ```if __name__ == '__main__':``` is when running a script with: python myscript.py. Otherwise from ipython I should use ```if __name__ == 'myscript':```. But I am looking for something easier so that I do not have to change the code – user3177899 Aug 24 '21 at 18:38

0 Answers0