background-process - 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.
推荐阅读
- php - 为什么在 Netbeans 中创建新项目后没有显示 index.php 文件?
- xamarin.forms - Xamarin 显示/隐藏密码
- reactjs - 此人员选取器的 defaultSelectedUser 属性的格式是什么?
- c# - 以编程方式获取 Microsoft Azure 的“始终开启”属性
- html - 在开发人员控制台中进行的更改在 angular mat-form-field 中的本地不起作用
- php - 无法使用 php html 在网格中显示图像
- javascript - 使用“esm”支持原生 ES6 模块的 Mocha 测试
- jsf - 将 HTTP 请求标头作为托管属性注入托管 bean
- angular - 不鼓励在 Angular 中为 httprequests 使用自定义管道?
- git - 为什么 git branch --merged 不显示分支,即使 git diff 显示没有区别?