python 2.7.5:在后台运行整个函数

问题描述

我是python的初学者。我想在后台运行整个功能(因为这可能需要一段时间甚至失败)。 这是函数

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

我想在后台将这个函数运行成一个循环:

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

在ksh中,我会编写类似backup $host & 的东西,并带有一个以$ host作为参数的函数

解决方法

您正在寻找的是在与我所了解的线程不同的线程中运行该函数。为此,您需要使用python线程模块。 这是您启动线程的方式:

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.