title: How to handle python script exit via terminating cmd/batch file abnormally
body: <p>I want to execute a python script on my windows startup.. which tracks my daily PC usage.</p>
  
  <p>Script execution notes the time when i start my PC as 'starttime'. and should note the time 'endtime' when i shut down my PC.</p>
  
  <p>Since script will be executed background, <strong>when i shutdown, batch file will be terminated abnormally(I've created batch file to run in startup).
  So I am facing trouble to handle such script exit to fetch the 'endtime'</strong> </p>
  
  <p>Though i tried 'sys','atexit' and even try,catch statements to have the end time. I am unable to fetch when the cmd(batch file cmd) is closed via 'X' button.  </p>
  
  <pre><code>
  import time
  
  with open("report_time.txt",'a') as f:
      f.write(str(int(time.time()))+ '\n')      # Start time
  
  def main():
      try:
          while(True):
              pass
      finally:
          with open("report_time.txt",'a') as f:
              f.write(str(int(time.time()))+ '\n')   # End time(This code works fine for keyboard interrupt)
  main()
  
  
  </code></pre>