python出现错误时退出程序

python出现错误时退出程序,python,error-handling,try-except,os.system,Python,Error Handling,Try Except,Os.system,我有许多py文件需要在一个py文件中运行。但我想提出一些条件,当程序在任何py文件的处理过程中出现错误时,需要退出程序。有人能帮我解决吗? 谢谢 5250A有错误-->退出程序 5250A无错误-->5250B有错误-->退出程序 5250A无错误-->5250B无错误-->5250C有错误-->退出程序 等等 更新日期:2021-03-12 main.py: import _5250A_1 import _5250A_2 import _5250A_3 import _5250A def m

我有许多py文件需要在一个py文件中运行。但我想提出一些条件,当程序在任何py文件的处理过程中出现错误时,需要退出程序。有人能帮我解决吗? 谢谢

5250A有错误-->退出程序

5250A无错误-->5250B有错误-->退出程序

5250A无错误-->5250B无错误-->5250C有错误-->退出程序

等等

更新日期:2021-03-12

main.py:

import _5250A_1
import _5250A_2
import _5250A_3
import _5250A

def main():
    try:
        _5250A_1.main()
        sleep(3)
        _5250A_2.main()
        sleep(3)
        _5250A_3.main()
        sleep(3)
        _5250.main()
    except Exception as details:
        print(f"Controller failed with error {details}")
        raise
    finally:
        print("Controller completed")

if __name__ == "__main__":  
    main()
_5250A

import os 
import glob
import pandas as pd
import openpyxl as xl;
import datetime

#Define some variable
activeUser = os.getlogin()
currDateTime = datetime.datetime.today() - datetime.timedelta(days = 31)
prevDateTime = datetime.datetime.today() - datetime.timedelta(days = 62)

#Merge 3 csv files into 1 csv file
os.chdir("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A")

allFiles = [i for i in glob.glob("*.{}".format("csv"))]
mergeCsv = pd.concat([pd.read_csv(f) for f in allFiles ])

#Export to csv file
mergeCsv.to_csv("5250A.csv", header = 1, index = False)


#Run Pandas and openpyxl to load csv file and convert to xlsx file format
csvFile = pd.read_csv ("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.csv")
csvFile.to_excel ("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx", sheet_name="5250A (Curr)", header = True, index = None)

wb1 = xl.load_workbook("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + prevDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx") 
ws1 = wb1.worksheets[0] 
wb2 = xl.load_workbook("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx") 
ws2 = wb2.create_sheet("5250A (Prev)")

mr = ws1.max_row 
mc = ws1.max_column 

for i in range (1, mr + 1): 
        for j in range (1, mc + 1): 
            ws2.cell(row = i, column = j).value = ws1.cell(row = i, column = j).value 

wb2.save("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx") 

#Run openpyxl to subtract cell value between 2 worksheet and save to xlsx file
def get_row_values(worksheet):

    result = []
    for i in worksheet.rows:
        row_data = []
        for j in i:
            row_data.append(j.value)
        result.append(row_data)
    return result

if __name__ == "__main__":

    wb = xl.load_workbook("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx")
    ws1 = wb.worksheets[0]
    ws2 = wb.worksheets[1]

    ws1_rows = get_row_values(ws1)
    ws2_rows = get_row_values(ws2)

    ws_new = wb.create_sheet('5250A (New)')

    ws_new.append(ws1_rows[0])
    for row in range(1, len(ws1_rows)):

        row_data = []
        for column, value in enumerate(ws1_rows[row]):
            if column == 0:
                row_data.append(value)
            else:
                if ws1_rows[row][0] == ws2_rows[row][0]:
                    row_data.append(value - ws2_rows[row][column])
        ws_new.append(row_data)
    wb.save("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx")

#Remove all csv files
os.remove("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.1.csv")
os.remove("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.2.csv")
os.remove("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.3.csv")
os.remove("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.csv")
应OP的要求,该评论得到了进一步的回应

要使此建议起作用,您需要将文件
5250A.py
重命名为
\u 5250A.py
等。这是为了使名称成为合法的Python标识符,不能以数字开头。它不必是
,它可以是你喜欢的任何东西

接下来,检查您的每个程序
\u 5250A.py
等是否遵循将所有模块级代码放在名为
main()
的函数中的常见Python样板,并在代码的最底部显示以下行:

if __name__ == "__main__":
    main()
如果你不明白为什么你需要这样做,停在这里,去看看,例如。这在无数的教程中都有解释,并且应该是您在构建程序时首先学到的东西之一。将模块级代码放入名为
main()
的函数中的原因是,您希望能够从模块外的调用运行该代码

完成此操作后,将
import
语句放入控制器程序中,以将模块代码
\u 5250A
等合并到该程序中:

import _5250A
import _5250B
import _5250C
import _5250D
。。。等

然后,您可以直接从控制器程序调用
main()
函数,而不是使用
os.system()
调用外部程序

def main():
    try:
        _5250A.main()
        _5250B.main()
        _5250C.main()
        _5250D.main()
    # the rest of the calls to other modules go here
    except Exception as details:
        print(f"Controller failed with error {details}")
        raise
    finally:
        print("Controller completed")

if __name__ == "__main__":
    main()
通过这种方式,子程序引发的任何异常都将通过堆栈跟踪正确报告,堆栈跟踪给出模块的名称、函数和失败的行。调用
os.system()
充其量只能得到数字0、1或2,而不会指出哪里出了问题或为什么出了问题

针对要修改的程序之一已经有一个测试
的问题,如果

您的程序
\u 5250A
包含:

if __name__ == "__main__":
    wb = xl.load_workbook("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx")
    # lots of other code, up to
    wb.save(...)
将此更改为:

def main():
    wb = xl.load_workbook("C:\\Users\\" + activeUser + "\\Documents\\" + "Print Count (" + currDateTime.strftime ("%b %Y") + ")\\5250A" + "\\5250A.xlsx")
    # lots of other code, up to
    wb.save(...)

if __name__ == "__main__":
    main()
现在这个节目还包括,

  • 在测试
    之前,如果uuuu name_uuuu==“uuuu main_uuuuuuu”:
    ,模块级的一块代码,开始定义一些变量,一直持续到
    定义行值(工作表):
  • 测试
    后,如果uuu name_uuuu==“uuuu main_uuuuu”:
    ,则模块级的代码块显然会进行清理
如果将这两块模块级代码都移动到函数
main()
,则不会造成任何伤害,因此现在看起来如下所示:

def main():

    #Define some variable
    activeUser = os.getlogin()
    # and everything up to and including to the line before the `def` statement
    wb2.save(...) 

    # Then the code that was inside the if-test:

    wb = xl.load_workbook(...)
    # lots of other code, up to
    wb.save(...)


    # and finally the code that was after the if-test:

    #Remove all csv files
    os.remove(...)
    # 3 more `os.remove()` calls
我怎么知道它不会造成伤害?很明显,如果不运行代码,我就不可能确定地知道这一点,因为我没有你的文件。但有可能做出一个自信的预测

很明显,尽管进行了
测试,但原始模块
5250A.py
并不打算导入。否则,它将不会无条件地在该点之前创建文件,并在该点之后清理文件。因此,这三个代码块基本上都是模块级的,如果uuu name uuuu==“uuuuu main uuuu”:
块,那么所有代码块都应该在
中,只要注意保持执行顺序,就可以安全地移动到
main()

这当然很容易测试。只需检查修改后的程序从命令行运行时是否产生与原始程序相同的输出

像这样移动代码很可能会在最初产生大量语法或运行时错误。这并不意味着不可能重组该计划;只是,在这个过程中,很容易出现剪切粘贴错误,甚至更容易引入压痕错误。我不会支持自己第一次就把这件事做好,我建议你也不要期望马上成功


我意识到,对您可能无法(或可能不再)完全理解的代码进行侵入性更改是一件棘手的事情,如果可能的话,还需要避免,而
os.system()
看起来是解决问题的简单方法。但是,
os.system()
无法将调用进程中的Python异常传递回调用程序。因此,正如您所发现的,这并不是一个完整的解决方案。

错误是什么?尝试用<代码>打印它,除了异常为e:打印(e)< /代码>,而不是使用<代码>操作系统(系统)(< /代码>),这是非常老套的,考虑使用模块<代码>子进程< /代码>。这将允许您运行文件并在每个文件之后检查返回代码。如果返回代码为非零,则跳过其余文件。但实际上,您不应该使用一个python程序来调用其他程序,就好像它们是子例程一样。如果您已使用
main()
函数(通常情况下)对所有程序进行编码,则只需导入所有子模块,然后调用
\u 5250A.main()
等。这将需要重命名子模块,因为它们的名称不能以数字开头。您可以将它们视为模块,导入它们是您的主脚本。“导入‘python 5250A’”@BoarGules:感谢您的回复。但是你能给我一个代码示例供我参考吗?谢谢。但我遇到了一个问题,这是py文件定义了if name=“main”,结果是无法为该部件运行。在这种情况下,您将现有
中的代码移动到名为
main()
的函数中。正如答案所说,将模块级代码放在函数中的原因是