尽管出现错误框,但强制脚本继续运行

时间:2015-06-01 17:23:39

标签: python python-2.7

我有一个脚本,它从两个不同的文件中读取信息,并将输出写入第三个文件。我有一个错误捕获(错误捕获的目标是显示脚本未处理的任何ID)在最后使用ctypes窗口消息框。目前,在我在错误消息框中单击“确定”之前,该脚本实际上并未完成对输出文件的写入。不管我按“确定”,我希望程序完成写入输出文件。这可能吗?

剧本:

'''select newest reference file'''
directory = 'C:\User\Python test\Folder1'

newest = max(glob.iglob(os.path.join(directory, '*.txt')), key=os.path.getctime)
timestamp = time.strftime("%Y_%m_%d - %H_%M_%S")


'''Get IDS to be read'''

idlist = open('C:\User\Python test\ID List.txt').read().splitlines()

'''Print or write lines associated with selected IDS'''


output = open('C:\User\Python test\%s.txt' % timestamp, 'w')

with open(newest, 'r') as f:
    head = f.readline().strip()
    output.writelines(head + "\n")
    for referenceline in f.read().strip().split("\n"):
        for ids in idlist:
            if ids in referenceline:
                output.writelines(referenceline.replace(" ", "") + "\n")
                idlist.remove(ids)
text = '\n'.join(idlist)
ctypes.windll.user32.MessageBoxW(0, u"%s" %text, u"IDs not found:", 0)

1 个答案:

答案 0 :(得分:0)

这个很简单。我只需要在错误捕获之前关闭文件。

代码:

output.close()
text = '\n'.join(idlist)
ctypes.windll.user32.MessageBoxW(0, u"%s" %text, u"IDs not found:", 0)