Search code examples
background-process

python 2.7.5: run a whole function in background


I am a beginner with python. I want to run a whole function in the background (because it can take a while or even fail). Here is the function:

def backup(str):
    command = barman_bin + " backup " + str
    log_maif.info("Lancement d'un backup full:")
    log_maif.info(command)
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = p.communicate()
    if p.returncode == 0:
        for line in output[0].decode(encoding='utf-8').split('\n'):
            log_maif.info(line)
    else:
        for line in output[0].decode(encoding='utf-8').split('\n'):
            log_maif.error(line)
    log_maif.info("Fin du backup full")
    return output

I want to run this function in the background into a loop :

for host in list_hosts_sans_doublon:
    backup(host) # <-- how to run the whole function in background ?

In ksh, I would have written something like backup $host & with backup a function that takes $host as an argument.


Solution

  • What you are looking for is to run the function in a different thread from what I understand. For this you need to use python thread module. This is how you start a thread:

    import threading
    def backup(mystring):
        print(mystring)
    
    host="hello"
    x = threading.Thread(target=backup, [host])
    x.start()
    Do what ever you want after this and the thread will run separately.