简体   繁体   中英

How to start a __name__ == '__main__': with specific inputs from another .py file?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM