首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否可以以typescript样式运行异步python脚本

是否可以以typescript样式运行异步python脚本
EN

Stack Overflow用户
提问于 2019-05-31 07:39:47
回答 1查看 189关注 0票数 0

目前,我有一个python脚本,它向微服务发出http请求。请求平均需要3秒。

这是我总结的python脚本。

def main():
  response = request_to_MS(url)

  # This process does not need the response of the microservice.
  some_process()

  # This is where i actually need a response from the microservice
  do_something_with_response(response)


main()

我希望我的脚本能够继续执行代码,并等待类似于typescript的请求响应。

/**
 * I'd like to write this kind of code in python.
 */
function get_data(): Promise<string>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('This is resolved');
    })
  })
}

async function main(){
  const data = get_data();
  console.log('Data variable stores my promise ', data);
  // Some process
  [1, 2, 3, 4, 5, 6 ,7 ,8].forEach((x: number) => console.log(x));
  // I need the promise value here
  console.log('En el await', (await data).length)
}


void main();

基本上,我寻找的是完成流程执行所需的时间和微服务的响应时间重叠,从而总体上允许更好的响应时间。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-31 07:47:30

使request_to_MS(url)成为async def协同例程,使用response = asyncio.create_task(request_to_MS(url))将其作为任务进行调度。

它将开始执行。现在,您可以继续运行some_process()。当您需要response时,只需执行以下操作

do_something_with_response(await response)

编辑:只有当main也是一个async def时,上述操作才有效,因为您只能在异步函数中使用awaits。调用asyncio.run(main()),而不是调用main()

总而言之:

async def request_to_MS(url):
    await asyncio.sleep(3)
    return 'some internet data'

async def main():
    response = asyncio.create_task(request_to_MS(url))
    # response is now a Task

    some_process()

    # if response isn't done running yet, this line will block until it is
    do_something_with_response(await response)

asyncio.run(main())

一个重要的警告,some_process不一定是一个协程,但如果它是一个阻塞函数(无论是通过CPU还是通过IO),它将永远不会产生任何周期来让response运行。如果它通过IO阻塞,也可以考虑将其设置为协程。如果没有异步支持它所执行的任何低级IO操作,或者如果它是受CPU限制的,可以考虑使用asyncio的run_in_executor

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56386950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档