【问题标题】:Can I run async code synchronously? [duplicate]我可以同步运行异步代码吗? [复制]
【发布时间】:2018-03-10 10:30:53
【问题描述】:

我想尝试pyppeteer 包,但感觉使用async 对我的小脚本来说有点矫枉过正。有没有办法同步运行异步代码?这是我尝试过的:

Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
[15:42:45]>>> import pyppeteer
[15:42:47]>>> browser = pyppeteer.launch()
[15:42:49]>>> pg = browser.newPage()
[15:42:52]>>> pg.goto('about:blank')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'coroutine' object has no attribute 'goto'
[15:42:55]>>> exit()
sys:1: RuntimeWarning: coroutine 'Browser.newPage' was never awaited

【问题讨论】:

    标签: python-3.x asynchronous synchronous


    【解决方案1】:

    你需要使用类似aioconsole 的包来实现同样的功能

    pip3 install aioconsole
    

    之后,您可以运行 apython 而不是运行 python,然后您可以在 Python REPL 中使用 await 语句

    >>> import pyppeteer
    >>> browser = pyppeteer.launch()
    >>> pg = await browser.newPage()
    >>> await pg.goto('http://tarunlalwani.com')
    <pyppeteer.network_manager.Response object at 0x10ee84860>
    >>> resp = _
    >>> vars(resp)
    {'_client': <pyppeteer.connection.Session object at 0x10ee5f940>, '_request': <pyppeteer.network_manager.Request object at 0x10ee840f0>, 'status': 200, '_contentPromise': <Future pending>, 'ok': True, 'url': 'http://tarunlalwani.com/', '_headers': {'date': 'Sat, 10 Mar 2018 02:28:04 GMT', 'content-encoding': 'gzip', 'last-modified': 'Sun, 10 Sep 2017 22:04:41 GMT', 'server': 'GitHub.com', 'x-github-request-id': 'E7AC:5FCC:6030CBE:86341C1:5AA342B4', 'vary': 'Accept-Encoding', 'content-type': 'text/html; charset=utf-8', 'access-control-allow-origin': '*', 'cache-control': 'max-age=600', 'transfer-encoding': 'chunked', 'expires': 'Sat, 10 Mar 2018 02:38:04 GMT'}}
    

    【讨论】:

    • OP 正在使用脚本,并且仅使用控制台会话来说明他们的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多