Python代码无法生成XML文件且print(count)无输出,是否与raise语句有关?
问题解答:raise语句导致XML文件无法生成的原因及修复
是的,无法创建XML文件完全是raise语句引发的问题
原因分析
- 执行流程被中断:当
sample_function()里的raise Exception(...)触发后,异常会直接终止整个程序的执行流程——函数跳出后,程序不会继续运行后面的if count > 0:代码块,XML生成逻辑根本没机会执行。 - 关于
print(count)的疑问:这段代码其实会执行,你看不到输出大概率是因为后续抛出的异常信息覆盖了它的输出,或者终端输出顺序导致它被忽略。
修复方案
要让XML文件正常生成,你需要阻止raise语句直接终止程序,有两种常见方式:
方式1:捕获函数抛出的异常
在调用sample_function()时,用try-except块捕获异常,这样程序会继续执行后续代码:
# 替换原有的sample_function()调用代码 try: sample_function() except Exception as e: print(f"捕获到异常: {e}")
方式2:移除不必要的raise语句
如果不需要向外抛出这个自定义异常,直接删除raise Exception("An error occurred in the script.")这一行即可,函数执行完成后程序会自然走到XML生成逻辑。
修改后的完整代码示例
import os import xml.etree.ElementTree as ET error_messages = [] count = 0 def sample_function(): try: result = 10 / 0 except Exception as e: print(f"An error occurred: {e}") error_messages.append(str(e)) global count count += 1 print(count) raise Exception("An error occurred in the script.") # 捕获异常避免程序终止 try: sample_function() except Exception as e: print(f"捕获到异常: {e}") if count > 0: print("Creating XML...") root = ET.Element("errors") subject = ET.Element("subject") subject.text = "DS Interface-v2.2.1 - ERROR: Python Script" salutation = ET.Element("salutation") salutation.text = "Dear Sir/Madam," body = ET.Element("body") logs_path = "${VMPROCESSES}\\TRUMPF\\DS-Interface-v2.2.1\\python\\logs" body.text = f"The Process has not been finished successfully. Having some issues regarding the Python script. Logfile can be found at location {logs_path}" root.append(subject) root.append(salutation) root.append(body) for error_message in error_messages: error_element = ET.Element("error") error_element.text = error_message root.append(error_element) output_directory = "c:/Users/PC/Desktop/gathering for ds/all-try python file/sample" os.makedirs(output_directory, exist_ok=True) xml_file_path = os.path.join(output_directory, "sample1_messages.xml") tree = ET.ElementTree(root) tree.write(xml_file_path) print(f"XML file created at {xml_file_path}")
内容的提问来源于stack exchange,提问作者Anjali Sinha
相关产品推荐
相关产品推荐

