2

I have a python script script_a.py that uses subprocess.call() that executes another script script_b.py as it's last instruction before ending. I need script_b.py to wait until script_a.py closes before proceeding with its own instructions. For this I am using a while loop within script_b.py. How can I do this? All of my current solutions I have tried have script_a.py waiting until script_b.py is finished before it closes itself. I have a feeling this might involve atexit() or something similar, but I am lost.

Many thanks!

KidMcC
  • 486
  • 2
  • 7
  • 17
  • it sounds like you are using the wrong construct ... I think you want `os.exec*` instead of `subprocess` ... – Joran Beasley Jul 21 '16 at 16:35
  • Got it. In the event that `script_b.py` has everything it needs to run defined within itself, then what am I expected to pass in the list of args that the exec* functions force me to pass? – KidMcC Jul 21 '16 at 16:52
  • you can probably just pass the ["python","script_b.py"] ... its been a while since i have done that ... – Joran Beasley Jul 21 '16 at 18:03

2 Answers2

1

Your script_a.py would be:

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

#continue doing stuff
Javier
  • 420
  • 2
  • 8
  • Where does this close `script_a.py` so the subprocess p can do its work? – KidMcC Jul 21 '16 at 17:06
  • Sorry I read it the other way around. If _a_ calls _b_ in the last instruction, and b needs to wait until a finishes you have an infinite loop. Just use another script _c_ that calls _a_ and then _b_. Any reason why you can't do that? – Javier Jul 21 '16 at 17:19
  • So there is no way to force script_a to continue on with its next instruction (which is `sis.exit()` regardless of when script_b finishes? – KidMcC Jul 21 '16 at 17:20
  • 1
    Use a script _c_ that calls both. – Javier Jul 21 '16 at 17:22
1

you could make some totally hacky crap

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"))

or instead of Popen just do

os.execl("/usr/bin/python","script_b.py")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179