从主文件执行Python文件并在任何文件中的断言失败时停止运行

问题描述 投票:0回答:1

我想从一个主文件运行几个Python文件。我正在使用my_module中的以下自定义函数来完成此操作:

import os

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")

在主文件中,我有:

from folder.my_module import run

run("first_file")
run("second_file")

first_filesecond_file内部,我写了几个断言。second_file不得运行,除非所有断言都已运行且未在first_file中引发错误。

通常,当任何文件中发生错误时,我希望整个程序停止运行。

我尝试过:

assert run("first_file"), "Error in file 1"
assert run("second_file"), "Error in file 2"

但是,无论第一个文件是否运行,该程序始终会停止运行。

我也尝试过:

try:
    run("first_file")
except:
    raise

try:
    run("second_file")
except:
    raise

但是这没有任何作用:即使second_file中的断言失败,first_file也会运行。

python import assert try-except
1个回答
0
投票

断言在这里总是会失败的,因为run返回None,这反过来会得出False

一个简单的解决方法:

def run(file):
    os.system(f"python3 -m folder.subfolder.{file}")
    return True

-2
投票
try:
  doSomeFunStuff()
except Exception, e:
  handleException(e)
  raise

OR,

import sys

try:
  print("something")
except:
  sys.exit(1) 
© www.soinside.com 2019 - 2024. All rights reserved.