1

I have a main.py in which a

if __name__ == '__main__':

is located to start the whole process. insted a normal def main() i need to use the if __name__ == '__main__': variante, because i am coding in spyder AND using multiprocessing at the same time (which would result in a mess otherwise).

I need to be able to just run this main.py file. (which works just fine, BUT...)

However at the same time i need to be able to call this

if __name__ == '__main__':

from outside by another .py file (lets call it optimize.py) with an optimizing loop to give the main.py different parameters.

is there a way to do this?

Benoid
  • 139
  • 1
  • 10

1 Answers1

1

Use a function that you call from your if __name__ == '__main__': condition:

Before:

if __name__ == '__main__':
    i = 5 
    j = 20
    m = 99
    # do A with i
    # do B with j
    # do C with m

After:

def start_me(i,j,m):
    # do A with i
    # do B with j
    # do C with m


if __name__ == '__main__':
    i = 5 
    j = 20
    m = 99
    start_me(i,j,m) 

If called directly it works with default parameters, if called from optimizer.py you simly use the function directly and provide parameters as you want.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • what in this case would be the "loop.py" and what the "main.py" – Benoid Jun 26 '20 at 10:36
  • @benoid both are main.py (once before, once after changes)- in loop.py you would do somehting like `from main import start_me` + `start_me(99,88,77)` – Patrick Artner Jun 26 '20 at 10:39
  • when I import this py file: doesnt the "if __name__ == '__main__': i = 5 j = 20 m = 99 start_me(i,j,m)" get called too then? (would be executing it twice) – Benoid Jun 26 '20 at 10:48
  • 1
    @Benoid the whole point of `if __name__ == '__main__':` is that when you do an `import yourfilename` in some other file, the `__name__` is NOT `'__main__'` but in that case is `yourfilename` ... see [here](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Patrick Artner Jun 26 '20 at 10:51