Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

How to get printed response from async function in Python

I want to get printed response of sync function. for that am using, StringIO.

import sys
from io import StringIO

def sample():
  print('started to fetch log!')
  print('response:body')
  print('status:200')

def get_log():
  sys.stdout = StringIO()
  sample()
  log = sys.stdout.getvalue()
  sys.stdout = sys.__stdout__
  return log

# in sync call,
out = get_log()
print(out)
started to fetch log!
response:body
status:200

but in async call, am unable to get those, created async wrapper for this sync function.

async def get():
  return asyncio.run(get_log()) 

return None. asyncio never running async function in synchronous. without running synchronous way, am unable to get print response.

Note: I need async wrapper to coupe with existing logics.

Upvotes: 0

Views: 315

Answers (1)

Korney Burau
Korney Burau

Reputation: 121

It is impossible to run regular sync function like that: asyncio.run(sync_func())

For implementing async call, you can use different methods, but because of example, it hard to understand what context of execution is here. Anyway there is one solution that should work. It is possible to execute sync function from async code using loop.run_in_executor for example:

import sys
from io import StringIO

def sample():
    print('started to fetch log!')
    print('response:body')
    print('status:200')

def get_log():
    sys.stdout = StringIO()
    sample()
    log = sys.stdout.getvalue()
    sys.stdout = sys.__stdout__
    return log

async def get():
    # get running event loop, in the case it has been already started
    loop = asyncio.get_running_loop()
    awaitable_res = loop.run_in_executor(None, get_log)
    res = await awaitable_res
    return res

if __name__ == '__main__':
    # if our script is executed as main, but also should work in another situations
    print_res = asyncio.run(get())
    print(print_res)  # print what you expected

Upvotes: 0

Related Questions