如何将Python脚本拆分为多个部分并在循环中导入它们?
首先,抱歉我这个标题有点傻 :) 下面是我的问题……其实这不是个问题。一切都在正常运行,但我想要更好的结构……
我有一个Python脚本,它每秒都会循环一次。在这个循环里,有很多很多的IF语句。请问我能不能把每个IF放在一个单独的文件里,然后在循环中引入它们?这样每次循环的时候,所有的IF语句也都会被执行……
我的脚本里有太多条件,而且每个条件之间都不太一样,所以我想要有一个模块的文件夹,比如mod_weather.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 个回答
我觉得你是在寻找类似于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()
),但这无论如何都是个坏主意。我敢打赌,我们可以想出一个更好的解决方案来解决你的 真正 问题 :)
把它们放在不同文件里的函数中,然后再导入使用:
"""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)
也许你在想,怎么使用自己的模块。你可以创建一个名为 'weather.py' 的文件,并在里面写一些合适的条件判断,比如:
""" 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)
,这个命令会重新加载模块并执行代码。但我想强调的是,使用外部模块的函数是更好的选择!