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

时间:2011-08-27 19:56:57

标签: 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中分开......

6 个答案:

答案 0 :(得分: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

同样适用于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),它实际上执行重新加载,包括代码执行。但是我不能过分强调使用外部模块的功能是一种更好的方法!

答案 1 :(得分:4)

将它们放在单独文件中的函数中,然后导入它们:

"""thing1.py
   A function to demonstrate
"""

def do_things(some_var):
    print("Doing things with %s" % (some_var))

``

"""thing2.py
   Demonstrates the same thing with a condition
"""

def do_things(some_var):
    if len(some_var) < 10:
        print("%s is < 10 characters long" % (some_var))
    else:
        print("too long")

``

"""main_program.py"""
import thing1, thing2

myvar = "cats"
thing1.do_things(myvar)
thing2.do_things(myvar)

答案 2 :(得分:1)

也许您只需要在循环中调用函数;并将这些功能放在其他模块中,您可以根据需要导入它们。

while true:
   if condition:
      from module_a import f
      f()
   if condition2
      from module_b import g
      g()

虽然以上是合法的Python,所以回答你的问题,你应该在实践中写下文件顶部的所有导入。

答案 3 :(得分:1)

我相信您正在寻找某种类似PHP的include()或C预处理器#include。您将拥有一个文件,例如下面的included.py

a = 2
print "ok"

和另一个具有以下代码的文件:

for i in values:
    import included

并且您希望结果等同于

for i in values:
    a = 2
    print "ok"

这是你在找什么?如果是这样......不,这是不可能的。一旦Python导入模块,就会执行模块的代码,并且在导入相同模式之后,只会检索已导入的模块实例。每次导入模块的代码都不会执行。

我可以发明一些疯狂的方法(让我们说,file.read() + eval(),或在导入的模块中调用reload()。)但无论如何这都是一个坏主意。我敢打赌,我们可以为您的真正的问题考虑更好的解决方案:)

答案 4 :(得分:0)

如果需要,您可以导入所需的模块,例如:

if condition:
    import weather
    ... do something

但是我不确定这是不是你真正想要的。

答案 5 :(得分:0)

  

我有一个python脚本,每秒循环“循环”。在循环   有很多IF。

然后您必须优化重复执行的测试。假设您的代码中有50个IF块,并且在for-loop的转向中,第N个条件为True:这意味着必须在测试第N个之前测试N-1个其他条件并触发执行相应的代码。

最好这样做:

# to_include.py

def func_weather(*args,**kwargs):
    # code
    return "I'm the weather"

def func_horoscope(*args,**kwargs):
    # code
    return "Give me your birth'date"

def func_gastronomy(*args,**kwargs):
    # code
    return 'Miam crunch'

def func_sports(*args,**kwargs):
    # code
    return 'golf, swimming and canoeing in the resort station'



didi = {'weather':func_weather, 'horoscope':func_horoscope,
        'gastronomy':func_gastronomy, 'sports':func_sports}

和主要模块:

# use_to_include.py

import to_include

x = 'sports'

y = to_include.didi[x]()
# instead of
# if  x =='weather'   : y = func_weather()
# elif x=='horoscope' : y = func_horoscope()
# elif x=='gastronomy': y = func_gastronomy()
# elif x=='sports'    : y = func_sports()

print y

结果

golf, swimming and canoeing in the resort station