如何在部分中拆分python脚本并在循环中导入部件?

Ned*_*nov 4 python import loops include

首先,抱歉我的愚蠢标题:)这是我的问题..其实这不是问题.一切正常,但我希望有更好的结构......

我有一个python脚本,每秒循环"循环".在循环中有许多IF.是否可以将每个IF放在一个单独的文件中,然后将其包含在循环中?所以这种方式每次循环"循环"时,所有的IF都将被传递.

在我的脚本中有太多的条件,并且它们通常与其他所有不同,所以我想要一些带有模块的文件夹 - mod_wheather.py,mod_sport.py,mod_horoscope.py等.

提前致谢.我希望我写的一切都可以理解......

编辑: 这是我现在拥有的结构示例:

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

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

   time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

如果我能有这样的东西会很好:

while True:
   import mod_news
   import mod_sport

   time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

并且第一个示例中的这些IF在文件mod_news.py,mod_sport.py中分开...

Rem*_*emi 6

也许你想知道如何使用你自己的模块.制作一个名为'weather.py'的文件,并让它包含适当的if语句,如:

""" 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
Run Code Online (Sandbox Code Playgroud)

同样适用于sport.py,horoscope.py等

然后你的主脚本看起来像:

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)
Run Code Online (Sandbox Code Playgroud)

编辑:根据您问题中的编辑进行编辑.请注意,我建议只在脚本开头导入所有模块一次,并使用其功能.这比通过导入执行代码更好.但是如果你坚持,你可以使用reload(weather),它实际上执行重新加载,包括代码执行.但我不能过分强调使用外部模块的功能是一个更好的方法!