python-3.x - 多线程 - 如何在 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
解决方案
如果您只想将打印语句组合在一起而不反映执行所需的暂停,那么您可以执行以下操作。请注意,如果您正在做的唯一事情是单个打印语句,那么您可能不需要锁。
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]
推荐阅读
- python-3.x - pydev eclipse 入门-“未找到使用 cython 的调试器加速”然后“发生另一个异常”
- c# - 如何从 UWP 截取屏幕截图?
- python - 如何在 Marshmallow 中反序列化不同的结构化 JSON 数据?
- javascript - 如何从脚本中删除 HTML?
- c++ - 运行查询后如何从sql表中获取列
- json - 如何在 SQL Server 2014 中使用 OPENJSON 或兼容的等效项?
- jenkins - 从詹金斯部署后缺少一件工件
- c# - 如何从 WebForms 的 DropDownList 中获取项目的 ID?
- python - 如何为集成测试设置时区
- c# - 在计算器应用程序中将运算符从减号更改为加号,反之亦然