我正在尝试运行以下代码,希望它异步运行。
import threading
import time
def mock_app(widgets=None, filters=None):
print('Mock app called')
task = threading.Thread(target=mock_app_handler(), args=())
task.start()
print('Thread spawned')
return "success"
def mock_app_handler():
# do something
print('doing something')
time.sleep(2)
print('done something')
print(mock_app())
但是,代码是同步执行的。我得到以下结果。
Mock app called
doing something
done something
Thread spawned
success
为什么会这样?我错过了什么吗?
更新: 我尝试设置 task.daemon = True。那也没有用。
答案 0 :(得分:2)
问题是,您调用的是函数 <div class="row">
<div class="col-md-4 ">
<div class="box ">
<div class="img-box">
<img src="images/solar.png" alt="solar">
</div>
<div class="detail-box">
<h5>
Solar Panel Systems
</h5>
<p>
Do you need something that isn't on the website? Do you need to to consult someone on<span id="dots5">...</span><span id="more5" style="display: none;"> something that has been bothering you with your devices, cameras, phones, alarms, solar panels? Do you need advice? Contact Us! IT'S FREE!!!</span>
</p>
<button type="button" id="solar" onclick="solar()">Read More</button>
</div>
</div>
</div>
</div>
而不是传递函数对象。 threading.Thread 中的 mock_app_handler
需要一个可调用对象。所以
代替
target
使用
task = threading.Thread(target=mock_app_handler(), args=())
此外,您不需要传递空的 task = threading.Thread(target=mock_app_handler)
,因为函数 args
不需要任何 mock_app_handler
。