如何将Python脚本分成几个部分并在循环中导入这些部分?

4

首先,对于我的愚蠢标题感到抱歉 :) 这是我的问题... 实际上这不是一个问题。一切都在运作,但我想有更好的结构...

我有一个Python脚本,每秒钟会有一个“循环”。在循环中有许多许多IFs。是否可能将每个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等文件中分开。


1
好像出了点问题... 你能否在帖子中添加一段相关的代码片段? - machine yearning
6个回答

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),这实际上执行了重新加载,包括执行代码。但我无法强调外部模块的函数是更好的选择!


谢谢!它有效。我使用了你的第一个例子。我只是在循环中执行 weather.check_all('sport')sport.check_all('sport'),它非常好用。我把 IF 语句放在外部模块中,这样就完美了。再次感谢你。 - Ned Stefanov
1
你提到了调试,如果你不使用像Eclipse with Pydev这样的调试器,你可以使用'import traceback'并在'try'语句后面放置while循环,比如说 'try: ..while loop .. except: traceback.print_exc()'。顺便说一下,如果它起作用了,我会很荣幸您能接受我的答案! - Remi
当然我会接受你的答案。我只是在做一些额外的测试 :) 谢谢你的建议。 - Ned Stefanov

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)

1
也许你只需要在循环中调用函数,并将这些函数放在其他模块中,根据需要进行导入。
while true:
   if condition:
      from module_a import f
      f()
   if condition2
      from module_b import g
      g()

虽然上述代码是合法的Python代码,也回答了你的问题,但在实践中,你应该将所有的导入语句放在文件顶部。


不要在函数中间进行导入,总是将它们放在顶部。每个导入语句都会重新执行被导入的文件。 - Brendan Long
也许在我的情况下这是一件好事。我想在循环中每次重新执行导入的文件,并检查IF条件... - Ned Stefanov
@Niki Stefanov - 你为什么不能直接调用一个函数呢? - Brendan Long

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()),但这无论如何都是个坏主意。我敢打赌我们可以想出更好的解决方案来解决你的真正问题 :)


是的,那就是我要找的... :( 謝謝你的回答。如我上面所寫,現在一切都運作正常,但我只是想將這個長腳本分成幾部分以便更容易調試.. 真可惜。 - Ned Stefanov
如果这是您正在寻找的内容,请查看我的答案编辑,包括重新加载语句。 - Remi

0

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

if condition:
    import weather
    ... do something

不过我不确定那是否是你真正想要的。


0
我有一个Python脚本,其中有一个每秒钟循环一次的循环。在循环中有许多IF语句块。

然后,您必须优化重复执行的测试。假设您的代码中有50个IF语句块,并且在for循环的一轮中,第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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接