如何编写既可按需运行又可被主脚本调用的导入函数?
假设我有一个主脚本,每周通过定时任务(cronjob)运行一次。这个脚本会从其他的Python文件中导入一些不同的功能,并按顺序运行这些功能。我还想能够在终端(Terminal)中随时运行主脚本中某些功能。那我该如何构建这个主脚本和包含功能的单独文件呢?下面是我目前的情况:
master_script.py
import do_bulk_things as b
import do_another_thing as a
b.do_first_bulk_thing()
b.do_second_bulk_thing()
if b.do_third_bulk_thing():
a.my_other_thing()
do_bulk_thinkgs.py
def do_first_bulk_thing():
# Code
def do_second_bulk_thing():
# Code
def do_third_bulk_thing():
# Code
if successful:
return True
do_another_thing.py
def my_other_thing():
# Code
如果我想运行 my_other_thing(),而不想执行整个 master_script.py,我应该在哪里定义和调用这些内容呢?被导入的文件里只有功能定义,所以我不能通过运行 python do_another_thing.py
来实际执行任何功能;而且我也不应该在 do_another_thing.py 中直接执行 my_other_thing(),因为那样在导入时就会自动运行。看起来我需要重新组织一下这些内容,但我需要一些最佳实践的建议。
1 个回答
1
我打算尝试回答我自己的问题,经过了一些进一步的研究,这让我找到了这个地方。在do_bulk_thinks.py和do_another_thing.py中执行定义和导入的函数,但使用__main__
来阻止这些函数在被导入时自动运行。这样master_script.py就不会改变,而其他文件会有:
do_bulk_things.py
def do_first_bulk_thing():
# Code
def do_second_bulk_thing():
# Code
def do_third_bulk_thing():
# Code
if successful:
return True
if __name__ == '__main__':
do_first_bulk_thing()
do_second_bulk_thing()
do_third_bulk_thing()
还有do_another_thing.py
def my_other_thing():
# Code
if __name__ == '__main__':
my_other_thing()