小编Vin*_*ent的帖子

将作业提交到asyncio事件循环

我想将作业从一个线程提交到一个asyncio事件循环(就像run_in_executor,反过来说).

以下是asyncio文档中有关并发和多线程的内容:

要从不同的线程安排回调,应使用BaseEventLoop.call_soon_threadsafe()方法.从不同的线程安排协程的示例: loop.call_soon_threadsafe(asyncio.async, coro_func())

这工作正常,但协程的结果丢失了.

相反,可以使用一个函数将完成的回调添加到async(或ensure_future)返回的未来,以便线程可以通过concurrent.futures.Future访问结果.

是否有特殊原因导致标准库中未实现此类功能?或者我错过了一种更简单的方法来实现这一目标?

python multithreading python-asyncio

8
推荐指数
1
解决办法
3857
查看次数

AttributeError的属性和__getattr__兼容性问题

我刚刚遇到了意想不到的行为.这是一个带有__getattr__方法和属性属性的简单类,里面有一个拼写错误:

class A(object):
    def __getattr__(self, attr):
        if not attr.startswith("ignore_"):
            raise AttributeError(attr)

    @property
    def prop(self):
        return self.some_typo

a = A() # Instantiating
a.ignore_this # This is ignored
a.prop # This raises an Attribute Error
Run Code Online (Sandbox Code Playgroud)

这是预期的结果(如果__getattr__被评论,我得到的结果):

AttributeError: 'A' object has no attribute 'some_typo'
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

AttributeError: prop
Run Code Online (Sandbox Code Playgroud)

我知道这与__getattr__捕获有关,AttributeError但这个问题有一个很好的和干净的解决方法吗?因为我可以向你保证,这是一个调试噩梦......

python properties

7
推荐指数
1
解决办法
1174
查看次数

Cython:纯C循环优化

引用Cython文档:

Cython recognises the usual Python for-in-range integer loop pattern:
    for i in range(n):
        ...
If i is declared as a cdef integer type, it will optimise this into a pure C loop
Run Code Online (Sandbox Code Playgroud)

我写了两个版本的简单Cython函数,一个使用Python range,另一个使用for-fromPyrex表示法(应该弃用):

 def loop1(int start, int stop, int step):
    cdef int x, t = 0
    for x in range(start, stop, step):
        t += x
    return t

def loop2(int start, int stop, int step):
    cdef int x, t = 0
    for x from …
Run Code Online (Sandbox Code Playgroud)

python optimization loops cython

5
推荐指数
1
解决办法
3669
查看次数

在 pycharm 调试器中调试异步程序

我的请求是从调试器和 pycharm 提示符中获取调试数据:

假设我有一个带有错误的旧式 python 同步程序:

   def listdir(self, remote_path):
         with ssh.connect(self.connection_settings['host'], username=self.connection_settings['username'],
                                    password=self.connection_settings['password']) as conn:
            with conn.start_sftp_client() as sftp:
                sftp.chdir(remote_path) # breakpoint here

                files = sftp.readdir()
                files_name = [file.filename for file in files]

                return files_name

Run Code Online (Sandbox Code Playgroud)

我会停止它,转到调试器,单击调试器控制台-> 显示 python 提示,然后在运行时调试我的问题:

> sftp.getcwd()
bad_user_location
> sftp.chdir(good_base_location)
> sftp.readdir()
Run Code Online (Sandbox Code Playgroud)

只需即时重写代码并测试状态和运行时即可。(这一直是我调试的方式,使用immediate windowMicrosoft 语言开发中的,以及 Python 和其他脚本语言中的 REPL。

现在我有一个异步程序:

  async def listdir(self, remote_path):
        async with asyncssh.connect(self.connection_settings['host'], username=self.connection_settings['username'],
                                    password=self.connection_settings['password']) as conn:
            async with conn.start_sftp_client() as sftp:
                await sftp.chdir(remote_path)  # breakpoint here


                files = await sftp.readdir() …
Run Code Online (Sandbox Code Playgroud)

python debugging asynchronous python-multithreading python-asyncio

5
推荐指数
1
解决办法
805
查看次数

何时以异步方式执行“ create_task()”中的任务?

在下面的代码中:

import asyncio

async def task_func():
    print('in task_func')
    return 'the result'


async def main(loop):
    print('creating task')
    task = loop.create_task(task_func())
    print('waiting for {!r}'.format(task))
    await asyncio.sleep(2)
    return_value = await task
    print('task completed {!r}'.format(task))
    print('return value: {!r}'.format(return_value))


event_loop = asyncio.new_event_loop()
try:
    event_loop.run_until_complete(main(event_loop))
finally:
    event_loop.close()
Run Code Online (Sandbox Code Playgroud)

当我执行代码时,结果如下:

creating task
waiting for `<Task pending coro=<task_func() running at <ipython-input-29-797f29858344>:1>>`
in task_func
task completed `<Task finished coro=<task_func() done, defined at <ipython-input-29-797f29858344>:1> result='the result'>`
return value: 'the result'
Run Code Online (Sandbox Code Playgroud)

但是我不明白您设置的代码何时loop.create_task(task_func())执行。具体来说,我假设当您将一个任务添加到事件循环中时,它很快就会执行,因此我认为in task_func是在之前打印的waiting for <Task...

然后我发现它 …

python asynchronous python-asyncio

4
推荐指数
1
解决办法
1840
查看次数