Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split python script in parts and to import the parts in a loop?

First, sorry for my stupid title :) And here is my problem.. Actually it's not a problem. Everything works, but I want to have better structure...

I have a python script with a loop "looped" each second. In the loop there are many many IFs. Is it possible to put each IF in a separate file and then to include it in the loop? So this way every time the loop is "looped", all the IFs will be passed, too..

There are too many conditions in my script and all of them are different generally from the otheres so I want to have some kind of folder with modules - mod_wheather.py, mod_sport.py, mod_horoscope.py, etc..

Thanks in advance. I hope I wrote everything understandable..

EDIT: Here is a structural example of what I have now:

while True:
   if condition=='news':
      #do something

   if condition=='sport':
      #so something else

   time.sleep(1)

It will be good if I can have something like this:

while True:
   import mod_news
   import mod_sport

   time.sleep(1)

And these IFs from the first example to be separated in files mod_news.py, mod_sport.py...

like image 311
Ned Stefanov Avatar asked Dec 17 '22 10:12

Ned Stefanov


1 Answers

perhaps you wonder how to work with your own modules in general. make one file named 'weather.py' and have it contain the appropriate if-statements like:

""" weather.py - conditions to check """

def check_all(*args, **kwargs):
    """ check all conditions """
    if check_temperature(kwargs['temperature']):
        ... your code ...

def check_temperature(temp):
    -- perhaps some code including temp or whatever ...
    return temp > 40

same for sport.py, horoscope.py etc

then your main script would look like:

import time, weather, sport, horoscope
kwargs = {'temperature':30}
condition = 'weather'
while True:
    if condition == 'weather':
        weather.check_all(**kwargs)
    elif condition == 'sport':
        sport.check_all()
    elif condition == 'horoscope':
        horoscope.check_all()
    time.sleep(1)

edit: edited according to the edit in your question. Note that I suggest importing all modules only one time, at the beginning of the script, and using its functions. This is better than executing code by importing. But if you insist, you could use reload(weather), which actually performs a reload including code execution. But I cannot stress too much that using functions of external modules is a better way to go!

like image 187
Remi Avatar answered May 03 '23 21:05

Remi