title: Closing ClientSession when keyboard interrupt
body: <p>I am making a discord bot with python. When a user types a command, this bot brings data from url and shows it. I use <code>aiohttp</code> for asynchronous http request, but documentation of <code>discord.py</code> says,</p>
  
  <blockquote>
    <p>Since it is better to not create a session for every request, you should store it in a variable and then call <code>session.close</code> on it when it needs to be disposed.</p>
  </blockquote>
  
  <p>So i changed all my codes from</p>
  
  <pre><code>async with aiohttp.ClientSession() as session:
      async with session.get('url') as response:
          # something to do
  </code></pre>
  
  <p>into</p>
  
  <pre><code># Global variable
  session = aiohttp.ClientSession()
  
  async with session.get('url') as response:
      # something to do
  </code></pre>
  
  <p>All http requests use globally defined <code>session</code>. But when i run this code and stop by keyboard interrupt(Ctrl + C), this warning messages are appeared.</p>
  
  <pre><code>Unclosed client session
  client_session: &lt;aiohttp.client.ClientSession object at 0x0000015A45ADBDD8&gt;
  Unclosed connector
  connections: ['[(&lt;aiohttp.client_proto.ResponseHandler object at 0x0000015A464925E8&gt;, 415130.265)]']
  connector: &lt;aiohttp.connector.TCPConnector object at 0x0000015A454B3320&gt;
  </code></pre>
  
  <p>How can i close <code>ClientSession</code> when program stops by keyboard interrupt?</p>
  
  <h1>What I tried:</h1>
  
  <p>I tried following but nothing worked well.</p>
  
  <ol>
  <li>Making a class and close in its <code>__del__</code>. <code>__del__</code> was not called when keyboard interrupt.</li>
  </ol>
  
  <pre class="lang-py prettyprint-override"><code>class Session:
      def __init__(self):
          self._session = aiohttp.ClientSession()
  
      def __del__(self):
          self._session.close()
  </code></pre>
  
  <ol start="2">
  <li>Infinite loop in <code>main</code>, and catch <code>KeyboardInterrupt</code>. Program is blocked with <code>bot.run()</code> so cannot reach to code.</li>
  </ol>
  
  <pre class="lang-py prettyprint-override"><code>from discord.ext import commands
  
  if __name__ == "__main__":
      bot = commands.Bot()
      bot.run(token) # blocked
      try:
          while(True):
              sleep(1)
      except KeyboardInterrupt:
          session.close()
  </code></pre>
  
  <ol start="3">
  <li>Close session when bot is disconnected. <code>on_disconnect</code> had been not called when keyboard interrupt.</li>
  </ol>
  
  <pre class="lang-py prettyprint-override"><code>@bot.event
  async def on_disconnect():
      await session.close()
  </code></pre>
  
  <ul>
  <li>edit: I missed <code>await</code> before <code>session.close()</code>, but this was just my mistake when I wrote this question. All I tried also didn't work well as i expected when i wrote correctly with <code>await</code>.</li>
  </ul>