简体   繁体   English

如果pywinauto抛出异常,则无法写入文件

[英]Writing to a file doesn't work if pywinauto throw an exception

I'm new in Python so can not definitely say where the problem is: in PyWinAuto or in my knowledge of Python. 我是Python新手,所以不能肯定地说出问题出在哪里:在PyWinAuto或我对Python的了解中。

I run the next script Windows (Python 3.5.2): 我运行下一个脚本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. 问题是log.errors已创建,但为空。 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. 将创建log.errors文件,并在其中包含预期的文本。 Not sure where the problem is. 不知道问题出在哪里。 How to change the script to write some info to the file if pywinauto throws an exception. 如果pywinauto引发异常,如何更改脚本以将一些信息写入文件。

f.write doesn't guarantee writing the data until you close the file ( f.close() ) or do f.flush() . 在关闭文件( f.close() )或执行f.flush()之前, f.write不能保证写入数据。 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. with部分退出时,此上下文管理器将自动关闭文件。 The file is guaranteed to close even if an exception is raised inside a with . 即使with引发异常,也可以保证关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM