Python 的文档说明time.monotonic():
返回单调时钟的值(以小数秒为单位),即不能倒退的时钟。时钟不受系统时钟更新的影响。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。
3.3 版本中的新功能。
版本 3.5 中的更改:该功能现在始终可用并且始终在系统范围内。
最后一句是否意味着对于 Python >= 3.5,返回的值time.monotonic()可以安全地在多个线程中使用和比较?
我正在使用ThreadPoolExecutorpythonconcurrent.futures并行抓取结果并将结果写入数据库。这样做时,我意识到如果其中一个线程失败,我将无法获得任何信息。我怎样才能正确地知道哪些线程失败以及为什么失败(因此使用“正常”回溯)?下面是一个最小的工作示例。
import logging
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%y-%m-%d %H:%M:%S', level=logging.INFO)
from concurrent.futures import ThreadPoolExecutor
def worker_bee(seed):
# sido is not defined intentionally to break the code
result = seed + sido
return result
# uncomment next line, and you will get the usual traceback
# worker_bee(1)
# ThreadPoolExecutor will not provide any traceback
logging.info('submitting all jobs to the queue')
with ThreadPoolExecutor(max_workers=4) as executor:
for seed in range(0,10):
executor.submit(worker_bee, seed)
logging.info(f'submitted, waiting for threads to finish')
Run Code Online (Sandbox Code Playgroud)
如果我在内部导入日志记录 …
Il 提出的问题,我不明白问题的真正原因(这似乎与我在子进程之一中使用烧瓶有关)。
请忽略此内容(由于赏金而无法删除)
本质上,当将 python 库作为模块运行时,我必须启动一些进程和/或池。
然而,因为这__name__ == '__main__'始终是正确的__main__.py,这被证明是一个问题(请参阅多处理文档:https ://docs.python.org/3/library/multiprocessing.html )
我尝试了多种解决方案,范围从: pytgquabr.com:8182/58288945/using-multiprocessing-with-runpy 到基于文件的互文本,只允许main的内容运行一次,但多处理仍然表现得很奇怪(例如进程几乎死掉)一旦它们启动且没有错误日志)。
知道解决这个问题的“正确”方法是什么吗?
python-module multiprocessing python-multithreading python-3.x
我正在使用 PyQt5 和 pyqtgraph 来绘制实时传感器数据。该图是更大的 PyQt5 应用程序的一部分,该应用程序用于与各种硬件交互并可视化传感器数据。
背景:下面的代码是一个非常简化的代码示例,负责查询传感器的数据,然后绘制瞬时位置及其移动平均值的图表。每 x 毫秒间隔在一个单独的线程中查询传感器。
问题: 图形和传感器读数按预期工作。然而,运行应用程序几秒钟后,pyqtgraph 停止更新并冻结。一旦图形冻结,我看到图形刷新/更新的唯一时间是当我尝试调整窗口大小或将焦点置于另一个窗口并重新聚焦回图形窗口时。在这种情况下,图表将仅更新一次并且不会继续刷新。
我在下面的链接中读到其他用户也有类似的问题。然而,建议的解决方案不是从单独的线程更新 GUI。就我而言,我不会从单独的线程更新图表。我仅使用单独的线程来收集传感器数据,然后发出带有新数据的信号。图的更新发生在主线程中。
import time
import numpy as np
from threading import Thread
import pyqtgraph as pg
import bottleneck as bn
import PyQt5
class MySensor():
def get_position(self, mean=0.0, standard_dev=0.1):
# Random sensor data
return np.random.normal(mean,standard_dev,1)[0]
class SignalCommunicate(PyQt5.QtCore.QObject):
# https://stackoverflow.com/a/45620056
got_new_sensor_data = PyQt5.QtCore.pyqtSignal(float, float)
position_updated = PyQt5.QtCore.pyqtSignal(float)
class LiveSensorViewer():
def __init__(self, sensor_update_interval=25):
# super().__init__()
# How frequently to get sensor data and update graph …Run Code Online (Sandbox Code Playgroud) Python 脚本多次执行 IO 密集型函数(数量级:5000 到 75000 之间的任意次数)。通过使用这仍然相当有效
def _iterator(): ... # yields 5000-75000 different names
def _thread_function(name): ...
with concurrent.futures.ThreadPoolExecutor(max_workers=11) as executor:
executor.map(_thread_function, _iterator(), timeout=44)
Run Code Online (Sandbox Code Playgroud)
如果用户按下 CTRL-C,它只会弄乱单个线程。我希望它停止启动新线程;并完成当前正在进行的线程或立即终止它们,等等。
我怎样才能做到这一点?
我正在尝试使用 python 通过 API 调用来抓取网站。由于要发出的请求数量很多,我正在考虑使用多线程或多处理来完成该任务。我对哪个更适合这项任务感到困惑。请您分享这方面的知识!
我需要设计一个脚本,该脚本使用终端的顶部部分作为输出,其中在无限循环中每秒打印一些行,底部部分不断接受用户输入并在上面的部分中打印它们(在常规周期中)输出)。
换句话说,我需要设计一种外壳。
我尝试使用简单的方法进行多线程处理,如下所示:
#!/usr/bin/python3
from math import acos
from threading import Thread
from random import choice
from time import sleep
from queue import Queue, Empty
commandQueue = Queue()
def outputThreadFunc():
outputs = ["So this is another output","Yet another output","Is this even working"] # Just for demo
while True:
print(choice(outputs))
try:
inp = commandQueue.get(timeout=0.1)
if inp == 'exit':
return
else:
print(inp)
except Empty:
pass
sleep(1)
def inputThreadFunc():
while True:
command = input("> ") # The shell
if command == 'exit':
return …Run Code Online (Sandbox Code Playgroud) python shell multithreading python-multithreading python-3.x
我有如下代码
threads = []
t = threading.Thread(target=Subscribe('username', "password", "topic", "host",port).start)
t1 = threading.Thread(target=Subscribe('username2', "password2", "topic2", "host",port).start)
threads.append(t)
threads.append(t1)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
Run Code Online (Sandbox Code Playgroud)
我的主题每 5 分钟发送一次数据。
当我使用上面的代码时,它无法正常工作,有时发送数据有时不发送数据。
但是,当我使用一个没有线程的主题时,它工作正常,并且数据每 5 分钟完美地传入一次。
我怎么解决这个问题?我想同时订阅两个主题。
我正在使用Paho进行MQTT
我的订阅类别是
class Subscribe:
def __init__(self, username, passowrd, topic, host, port):
self.username = username
self.password = passowrd
self.topic = topic
self.host = host
self.port = port
def start(self):
self.mqttc = mqtt.Client(client_id="Python")
self.connected = False
self.mqtt_message = …Run Code Online (Sandbox Code Playgroud) 只是一个小问题。
我使用大约 6 个线程,所有线程每隔几秒打印一些内容。有时它们会在同一行上打印,如下所示:
OUTPUT
OUTPUT
OUTPUTOUTPUT
OUTPUT
OUTPUT
Run Code Online (Sandbox Code Playgroud)
如您所见,这会留下一个空行和一个双打印。有什么办法可以确保这种情况不会发生吗?我看到有句话说:
print("OUTPUT", end="\n")
Run Code Online (Sandbox Code Playgroud)
这不起作用,所以我又回到了堆栈溢出!
下面的测试通过了,但我怀疑我是否正确使用了 asyncio:
import asyncio
import threading
import pytest
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def websocket_server():
async with websockets.serve(echo, "localhost", 8765):
await asyncio.Future()
def _run_server():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(websocket_server())
loop.close()
@pytest.fixture
def run_server():
thread = threading.Thread(target=_run_server)
thread.start()
yield thread
# no idea how to stop the loop here
thread.join()
@pytest.mark.asyncio
async def test_websocket(run_server):
async with websockets.connect("ws://localhost:8765") as websocket:
await websocket.send("Hello!")
response = await websocket.recv()
assert response == "Hello!"
Run Code Online (Sandbox Code Playgroud)
(注意:为了停止循环,我尝试了此处提出的解决方案(How …
python websocket pytest python-multithreading python-asyncio