首页 > 解决方案 > 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 作为参数。

标签: background-process

解决方案


您正在寻找的是在与我理解不同的线程中运行该函数。为此,您需要使用 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. 

推荐阅读