Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - Why am I getting NotImplementedError with async and await on Windows?

I have this code:

import os
import time
import asyncio


async def run_command(*args):
    """
    Example from:
        http://asyncio.readthedocs.io/en/latest/subprocess.html
    """
    # Create subprocess
    process = await asyncio.create_subprocess_exec(
        *args,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE)

    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()

    # Result
    result = stdout.decode().strip()

    # Return stdout
    return result


def run_asyncio_commands(tasks):
    """Run tasks using asyncio and return results"""
    loop = asyncio.get_event_loop()
    commands = asyncio.gather(*tasks)  # Unpack list using *
    results = loop.run_until_complete(commands)
    loop.close()
    return results


if __name__ == '__main__':

    start = time.time()

    cmds = [
        ['du', '-sh', '/Users/fredrik/Desktop'],
        ['du', '-sh', '/Users/fredrik'],
        ['du', '-sh', '/Users/fredrik/Pictures']
    ]

    tasks = []
    for cmd in cmds:
        tasks.append(run_command(*cmd))
    results = run_asyncio_commands(tasks)
    print(results)

    end = time.time()
    print('Script ran in', str(end - start), 'seconds')

When I run the that code in Python 3.6.1 on my mac, I get this:

['780K/Users/fredrik/Desktop', '46G/Users/fredrik', '52M/Users/fredrik/Pictures']
Script ran in 6.405519008636475 seconds

But when I run the same script on Windows (but with the du commands substituted to something which works on Windows), also with Python 3.6.1, I get this:

Traceback (most recent call last):
  File "C:UsersiruserDesktopasynciotest.py", line 66, in <module>
    results = run_asyncio_commands(tasks)
  File "C:UsersiruserDesktopasynciotest.py", line 41, in run_asyncio_commands
    results = loop.run_until_complete(commands)
  File "C:Usersfredrikcondaenvsdev_py36libasyncioase_events.py", line 466, in run_until_complete
    return future.result()
  File "C:UsersiruserDesktopasynciotest.py", line 16, in run_command
    stdout=asyncio.subprocess.PIPE)
  File "C:Usersfredrikcondaenvsdev_py36libasynciosubprocess.py", line 225, in create_subprocess_exec
    stderr=stderr, **kwds)
  File "C:Usersfredrikcondaenvsdev_py36libasyncioase_events.py", line 1190, in subprocess_exec
    bufsize, **kwargs)
  File "C:Usersfredrikcondaenvsdev_py36libasynciocoroutines.py", line 210, in coro
    res = func(*args, **kw)
  File "C:Usersfredrikcondaenvsdev_py36libasyncioase_events.py", line 340, in _make_subprocess_transp
ort
    raise NotImplementedError
NotImplementedError

This is what I substitute the Unix commands with on Windows:

cmds = [['C:/Windows/system32/HOSTNAME.EXE']]

Windows version info:

Python 3.6.1 | packaged by conda-forge | (default, May 23 2017, 14:21:39) [MSC v.1900 64 bit (AMD64)] on win32
Windows 10 Pro, version 1703, OS build 15063.413
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Different event loops are implemented differently. Some of them have restrictions (sometimes OS-related). By default, Windows uses SelectorEventLoop and as you can see in doc:

SelectorEventLoop has the following limitations:

  • SelectSelector is used to wait on socket events: it supports sockets and is limited to 512 sockets.
  • loop.add_reader() and loop.add_writer() only accept socket handles (e.g. pipe file descriptors are not supported).
  • Pipes are not supported, so the loop.connect_read_pipe() and loop.connect_write_pipe() methods are not implemented.
  • Subprocesses are not supported, i.e. loop.subprocess_exec() and loop.subprocess_shell() methods are not implemented.

To run your code in Windows you can use alternative event loop available by default - ProactorEventLoop.

Replace line:

loop = asyncio.get_event_loop()

with this:

loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)

Your code will work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...