Skip to main content
 首页 » 编程设计

python之如果正在执行另一个脚本,则阻止 python 脚本运行

2025年01月19日14davidwang456

我正在开发的一个更大的系统中有两个脚本。让我们调用一个 foo.py 和另一个 bar.py。

foo 创建文件,bar 随后将读取和删除这些文件。现在,如果 foo 正在运行并处理一个文件,bar 会在 foo 完成之前处理同一个文件,从而把事情搞砸。

foo 和 bar 由其他东西自动启动,而不是由运行它们的人手动启动。 如果 foo 正在处理文件,我如何确保 bar 不会启动?

我考虑过编辑它们,以便 foo 在执行开始时将 1 写入文本文件,在执行结束时写入 0,并使 bar 读取文本文件以检查它是否可以启动。但我不确定这是最优雅的解决方案,而且如果 foo 在执行过程中失败,我也不想阻止 bar,留下文件在 1。

请您参考如下方法:

你可以使用subprocess

在你的主文件中:

import subprocess 
 
 
def main(): 
    p = subprocess.Popen(['python', 'foo.py']) 
    res = p.wait() 
    if res == 0: 
        print("foo did ok") 
        # execute bar.py 
    else: 
        print("foo failed along the way") 

在 foo.py 中,如果一切正常,确保以代码 0 退出: exit(0)(这将返回到主脚本中的res)。

如果你想在等待 foo 完成时做其他事情,你也可以使用 poll()。

def main(): 
    p = subprocess.Popen(['python', 'foo.py']) 
 
    while not p.poll()==0: 
        print("wait for foo") 
        #do some other magic. but make sure to have a break condition 
        # e.g. if foo takes too long.