I'm new in Python so can not definitely say where the problem is: in PyWinAuto or in my knowledge of Python.
I run the next script Windows (Python 3.5.2):
#!/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()
The problem is the log.errors is created, but empty. If I change the code like this:
# LicenseForm.OK.Click()
raise pywinauto.findbestmatch.MatchError
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.
f.write
doesn't guarantee writing the data until you close the file (f.close()
) or do f.flush()
. But I'd recommend you the following way:
with open('R:\Temp\diagnostic\log.errors', 'w') as f:
f.write('Exception raised')
This context manager will close the file automatically when exiting from with
section. The file is guaranteed to close even if an exception is raised inside a with
.