sgld 最近的时间轴更新
sgld

sgld

🏢  CN / 牛马
V2EX 第 644240 号会员,加入于 2023-08-18 13:03:30 +08:00
sgld 最近回复了
3 天前
回复了 sgld 创建的主题 Python 关于 Python 协程的 event loop 与 future
@cyaki 是哪位呀
3 天前
回复了 sgld 创建的主题 Python 关于 Python 协程的 event loop 与 future
@lxy42 好的好的,我看看这个,🙏感谢资源
3 天前
回复了 sgld 创建的主题 Python 关于 Python 协程的 event loop 与 future
用 ai 辅助修改了下代码,然后加了一些 print ,直观的了解了下执行流程

import time
import random
from collections import deque
from itertools import count
import heapq

count_id = count(1)

class Future:
def __init__(self):
self._done = False
self._result = None
self._callbacks = []
self._cancelled = False
self._id = f'Future-{next(count_id)}'

def add_done_callback(self, fn):
if self._done:
fn(self)
else:
self._callbacks.append(fn)

def set_result(self, result):
self._result = result
self._done = True
for cb in self._callbacks:
cb(self)

def __await__(self):
if not self._done:
print(f"Future {self._id} is not done, waiting...")
# 这里的 self 是一个 Future 对象, 需要在调用时使用 await 关键字
yield self
return self._result

class Task(Future):
def __init__(self, coro):
super().__init__()
self.coro = coro
print(f"任务初始化, 任务 ID: {self._id}")
loop.call_soon(self.run)

def run(self):
try:
result = self.coro.send(None)
except StopIteration as e:
"""执行"""
print(f"任务 {self._id} 执行完毕, 结果: {e.value}")
self.set_result(e.value)
else:
if isinstance(result, Future):
result.add_done_callback(self._wakeup)
print(f"Task {self._id} is waiting for Future {result._id}")
def _wakeup(self, future: Future):
"""
This method is called when the future is done.
It schedules the task to run again.
"""
print(f"等待完成, 唤醒任务 {self._id}, 结果: {future._result}")
loop.call_soon(self.run)

class EventLoop:
def __init__(self):
self._ready = deque()
self._scheduled = []
self._stopped = False

def call_soon(self, callback, *args):
self._ready.append((callback, args))

def call_later(self, delay, callback, *args):
heapq.heappush(self._scheduled,
(time.time() + delay, callback, args))

def stop(self):
self._stopped = True

def create_task(self, coro):
return Task(coro)

def run_forever(self):
while not self._stopped:
self.run_once()

def run_once(self):
now = time.time()
while self._scheduled and self._scheduled[0][0] <= now:
_, cb, args = heapq.heappop(self._scheduled)
self._ready.append((cb, args))

num = len(self._ready)
for _ in range(num):

# 取出一个任务, 执行它
cb, args = self._ready.popleft()
print(f"----> 执行 {cb}({args}) ---->")
cb(*args)

async def smallrun():
print("Start smallrun")

# 创建一个 Future 对象
# 代表一个将来的结果, 但是现在还不知道结果是什么
fut = Future()
print(f"Future {fut._id} created")
# 功能模拟 --- 随机延迟, 模拟 IO 操作
# IO 结束以后, 调用 fut.set_result(None)
delay = random.random()
loop.call_later(delay, fut.set_result, None)

await fut
print("End smallrun after", delay)
return delay

async def bigrun():
print("Start bigrun")
delay = await smallrun()
print("End bigrun with", delay*10)
return delay * 10

async def main_task():
print("Main task start")
result = await bigrun()
print("Final result:", result)

if __name__ == "__main__":
loop = EventLoop()
loop.create_task(main_task())

# 2.1 秒后停止事件循环
loop.call_later(2.2, loop.stop)
loop.run_forever()
3 天前
回复了 sgld 创建的主题 Python 关于 Python 协程的 event loop 与 future
@Trim21 源码太复杂了,有涉及到很多情况,现在在看上面视频里面 up 写的简易版本的,
3 天前
回复了 sgld 创建的主题 Python 关于 Python 协程的 event loop 与 future
@thevita 感谢大佬,我理解一下
一次成功,hhh
```python
import csv


with open("test.csv", "r", encoding="latin-1") as f:
reader = csv.reader(
f,
delimiter=",",
quotechar='"',
doublequote=True,
escapechar="\\",
skipinitialspace=True,
)
try:
for row in reader:
cleaned_row = [field.strip().replace("\n", " ") for field in row]
print("Parsed Columns:")
for idx, col in enumerate(cleaned_row, 1):
print(f"Column {idx}: {col}")
except csv.Error as e:
print(f"CSV 解析错误: {e}")
```

```
Parsed Columns:
Column 1: 37929
Column 2: 301
Column 3: 00 40 00 00 00 B9 30 30 3A 30 30 3A 30 32 3A 31 31 33 20 28 32 34 34 30 29 56 20 65 76 65 6E 74 20 36 35 30 20 70 75 62 6C 69 63 3A 38 2C 31 20 30 20 22 64 69 73 6B 3A 38 2C 30 22 20 22 22 0A
Column 4: [2025/02/20 12:00:51]
Column 5: 9250
Column 6: DATA LOG
Column 7: 00:00:02:113 (2440)V event 650 public:8,1 0 disk:8,0" ""
```
可以尝试让 ai 写个辅助代码,规范一下 csv 格式,最后一列里面有个 `,` 应该是这里导致第 7 列变成了第 7 列和第 8 列
@blankmiss 有用感觉还行吧 hhh
@Nasei 还真是,qwq ,原来是已经安装的右键没有 vsix 。搜了一个未安装的,确实右键就有这个下载选项
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2737 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 14ms · UTC 14:30 · PVG 22:30 · LAX 07:30 · JFK 10:30
Developed with CodeLauncher
♥ Do have faith in what you're doing.