title: Python asyncio (aiohttp, aiofiles)
body: <p>I seem to be having a difficult time understanding pythons asyncio. I have not written any code, as all the examples I see are for one-off runs. Create a few coroutine's, add them to an event loop, then run the loop, they run the tasks switching between them, done. Which does not seem all that helpful for me.</p>
  
  <p>I want to use asyncio to not interrupt the operation in my application (using pyqt5). I want to create some functions that when called run in the asyncio event loop, then when they are done they do a callback.</p>
  
  <p>What I imagine is. Create a separate thread for asyncio, create the loop and run it forever. Create some functions <code>getFile(url, fp)</code>, <code>get(url)</code>, <code>readFile(file)</code>, etc. Then in the UI, I have a text box with a submit button, user enters url, clicks submit, it downloads the file.</p>
  
  <p>But, every example I see, I cannot see how to add a coroutine to a running loop. And I do not see how I could do what I want without adding to a running loop. </p>
  
  <pre><code>#!/bin/python3
  import asyncio
  import aiohttp
  import threading
  
  loop = asyncio.get_event_loop()
  
  def async_in_thread(loop):
      asyncio.set_event_loop(loop)
      loop.run_forever()
  
  async def _get(url, callback):
      print("get: " + url)
      async with aiohttp.ClientSession() as session:
          async with session.get(url) as response:
              result = await response.text()
              callback(result)
              return
  
  def get(url, callback):
      asyncio.ensure_future(_get(url, callback))
  
  thread = threading.Thread(target=async_in_thread, args=(loop, ))
  
  thread.start()
  
  def stop():
      loop.close()
  
  def callme(data):
      print(data)
      stop()
  
  get("http://google.com", callme)
  
  thread.join()
  </code></pre>
  
  <p>This is what I imagine, but it does not work.</p>