python - 如何将 python 脚本分成几部分并循环导入这些部分?

标签 python loops import 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)

如果我能有这样的东西就好了:

while True:
   import mod_news
   import mod_sport

   time.sleep(1)

第一个示例中的这些 IF 将在文件 mod_news.py、mod_sport.py 中分离...

最佳答案

也许您想知道通常如何使用您自己的模块。 制作一个名为“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

同样适用于 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)

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

关于python - 如何将 python 脚本分成几部分并循环导入这些部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7216993/

相关文章:

c++ - 使用花括号分隔我想在 C++ 中多次使用的变量

将 ASC 文件读入 R

php - 使用更新从 CSV 导入到 MySQL

javascript - 无法在 import 或 require 中连接 var

python - Tensorflow 动态循环神经网络 (LSTM) : how to format input?

Python 可移植、Linux 和 Windows

python - 在 Python 中进行这种排序的标准方法是什么?

python - BeautifulSoup:获取空变量

java - 如何退出Java循环?基本猜谜游戏中的 while 循环

MATLAB:更快的零矩阵预分配