执行另一个 python 脚本,然后关闭当前脚本

Execute another python script, then shut down current script

我有一个 python 脚本 script_a.py,它使用 subprocess.call() 执行另一个脚本 script_b.py 作为结束前的最后一条指令。我需要 script_b.py 等到 script_a.py 关闭后再继续执行它自己的指令。为此,我在 script_b.py 中使用了一个 while 循环。我怎样才能做到这一点?我尝试过的所有当前解决方案都 script_a.py 等到 script_b.py 完成后才会自行关闭。我觉得这可能涉及 atexit() 或类似的东西,但我迷路了。

非常感谢!

您的 script_a.py 将是:

import subprocess
#do whatever stuff you want here
p = subprocess.Popen(["python","b.py"])
p.wait()
p.terminate()

#continue doing stuff

你可以做一些完全 hacky 废话

script_b.py

while not os.path.exists("a.done"):pass
time.sleep(0.2) # a little longer just to be really sure ...
os.remove("a.done")
... # rest of script b

script_a.py

import atexit
atexit.register(lambda *a:open("a.done","w"))

或者代替 Popen

os.execl("/usr/bin/python","script_b.py")