Search code examples
pythonpython-3.xterminateos.system

How to Terminate a Python program before its child is finished running?


I have a script that is supposed to run 24/7 unless interrupted. This script is script A. I want script A to call Script B, and have script A exit while B is running. Is this possible? This is what I thought would work

#script_A.py
while(1)
    do some stuff
    do even more stuff
    if true:
        os.system("python script_B.py")
        sys.exit(0)


#script_B.py
time.sleep(some_time)
do something
os.system("python script_A.py")
sys.exit(0)

But it seems as if A doesn't actually exit until B has finished executing (which is not what I want to happen). Is there another way to do this?


Solution

  • What you are describing sounds a lot like a function call:

    def doScriptB():
      # do some stuff
      # do some more stuff
    
    def doScriptA():
      while True:
        # do some stuff
        if Your Condition:
          doScriptB()
          return
    
    while True:
      doScriptA()
    

    If this is insufficient for you, then you have to detach the process from you python process. This normally involves spawning the process in the background, which is done by appending an ampersand to the command in bash:

    yes 'This is a background process' &
    

    And detaching said process from the current shell, which, in a simple C program is done by forking the process twice. I don't know how to do this in python, but would bet, that there is a module for this.

    This way, when the calling python process exits, it won't terminate the spawned child, since it is now independent.