首页 > 解决方案 > 多线程 - 如何在 python 中的线程调用期间控制函数的打印语句

问题描述

我正在使用 ThreadPoolExecuter 来并行执行打印语句并执行 sql 的函数。我想管理函数中的打印语句。例如

def Func(host,sql):
   print ('Executing for %s ' %host)
   SQL = Execute(host,SQL) -- connecting to DB
   print SQL

main():
sql = 'show databases;'

hostList = ['abc.com','def.com','ghi.com','jkl.com']
 with concurrent.futures.ThreadPoolExecutor() as executor:
     future = [executor.submit(Func,acct ,host,sql) for host in hostList]

这里对于 hostList 中的 4 个项目,它执行线程并并行执行函数 Func,但打印结果如下

Executing for abc.com
Executing for def.com
Executing for ghi.com
Executing for jkl.com

then 
SQL output 1
SQL output 2
SQL output 3
SQL output 4

我希望打印的功能如下所示

Executing for abc.com
 SQL output 1

Executing for def.com
 SQL output 1

Executing for ghi.com
 SQL output 1

Executing for jkl.com
 SQL output 1

标签: python-3.xmultithreadingthreadpoolpython-multithreadingthreadpoolexecutor

解决方案


如果您只想将打印语句组合在一起而不反映执行所需的暂停,那么您可以执行以下操作。请注意,如果您正在做的唯一事情是单个打印语句,那么您可能不需要锁。

import concurrent.futures
import threading
import random
import time

def Func(account, host, sql, lock):
    seconds = random.randint(1, 10)
    time.sleep(seconds)
    result = "Result of executing \"{}\" took {} seconds".format(sql, seconds)

    ## -------------------------------
    ## Probably don't need to lock if you combine these into one statement
    ## -------------------------------
    with lock:
        print('Executing for %s ' % host)
        print("\t{}\n".format(result))
    ## -------------------------------

lock = threading.Lock()
hostList = ['abc.com','def.com','ghi.com','jkl.com']
with concurrent.futures.ThreadPoolExecutor() as executor:
    future = [executor.submit(Func, "acct" , host, "somesql", lock) for host in hostList]

推荐阅读