Writing to a file doesn't work if pywinauto throw an exception
<p>I'm new in Python so can not definitely say where the problem is: in PyWinAuto or in my knowledge of Python.</p>

<p>I run the next script Windows (Python 3.5.2):</p>

<pre><code>#!/usr/bin/env python3
import os
import sys
import pywinauto

def testLicenseForm():
    app = pywinauto.Application().Start('Calc.exe')

    try:
        LicenseForm = app['Nonsense name']
        LicenseForm.OK.Click()
 #       raise pywinauto.findbestmatch.MatchError
 #       raise pywinauto.timings.TimeoutError
    except (pywinauto.timings.TimeoutError, pywinauto.findbestmatch.MatchError) as e:
        f = open('R:\Temp\diagnostic\log.errors', 'w')
        f.write('Exception raised')
        sys.exit('Error in script'.format(__file__))

if __name__ == '__main__':
    testLicenseForm()
</code></pre>

<p>The problem is the log.errors is created, but empty. If I change the code like this:</p>

<pre><code>#    LicenseForm.OK.Click()
     raise pywinauto.findbestmatch.MatchError
</code></pre>

<p>the log.errors file is created and contains the expected text in it.
Not sure where the problem is. How to change the script to write some info to the file if pywinauto throws an exception.</p>

<p><code>f.write</code> doesn't guarantee writing the data until you close the file (<code>f.close()</code>) or do <code>f.flush()</code>. But I'd recommend you the following way:</p>

<pre><code>with open('R:\Temp\diagnostic\log.errors', 'w') as f:
    f.write('Exception raised')
</code></pre>

<p>This context manager will close the file automatically when exiting from <code>with</code> section. The file is guaranteed to close even if an exception is raised inside a <code>with</code>.</p>

python windows fwrite pywinauto