os.system 调用 python 失败后继续执行脚本

Continuing script after failure on os.system call python

我编写了一个脚本来扫描文本文件目录,如果找到它们,它会创建一个系统调用 运行 txt 文件上的脚本。我仍在处理一些导致我的一些系统调用失败的小错误。但是,我希望这不会杀死我的脚本。我只想被告知错误,然后继续我的生活。似乎任何成功的调用 returns 0 而任何导致错误 returns n 的调用。我试图将结果与 0 进行比较,但它永远不会那么远。关于如何完成此操作的任何建议?

import sys, getopt, os

def main(argv):

    def scan_dir(path):
            temp_path = path
            print temp_path
            for file in os.listdir(path):
                    temp_path += file
                    if file.endswith(".txt"):
                            result = os.system("python callscript.py -i %s" % path)
                            if result != 0
                                    print "Error!"

                    temp_path = path


    def usage():
            print "usage:  dostuff.py [hi:]\n \
                  \t -h\t print usage\n \
                  \t -i\t directory path\n"
            sys.exit(2)

    if(len(argv) == 0):
            usage()

    path = ''

    try:
            opts, args = getopt.getopt(argv,"hi:",["path="])
    except getopt.GetoptError:
            usage()

    for opt, arg in opts:
            if opt == '-h':
                    usage()

            elif opt in ("-i", "--ipath"):
                    path = arg
    if path.endswith('/') == False:
            path += '/'

    scan_dir(path)



if __name__ == "__main__":
main(sys.argv[1:])

您应该特别使用 subprocess 模块 check_call,捕获一个 CalledProcessError,它会因任何非零退出状态而被引发:

 from subprocess import check_call,CalledProcessError      

  try:
       check_call(["python", "callscript.py", "-i",path])
  except CalledProcessError as e:
       print e.message

理解你的代码并不容易,我建议不要将所有其他函数嵌套在 main 中。我还会使用 glob 来查找 txt 文件:

from glob import  glob

def scan_dir(path):
    files = (os.path.join(path,f) for f in glob(os.path.join(path,"*.txt")))
    for fle in files:    
        try:
            check_call(["python", "callscript.py", "-i", fle])
        except CalledProcessError as e:
            print e.message

def usage():
    print "usage:  dostuff.py [hi:]\n \
          \t -h\t print usage\n \
          \t -i\t directory path\n"
    sys.exit(2)


if __name__ == "__main__":
    args = sys.argv[1:]
    if not args:
        usage()
    path = ''
    try:
        opts, args = getopt.getopt(args, "hi:",["path="])
    except getopt.GetoptError:
            usage()

    for opt, arg in opts:
        if opt == '-h':
                usage()
        elif opt in ("-i", "--ipath"):
                    path = arg
    if not path.endswith('/'):
            path += '/'
    scan_dir(path)

要在不停止主进程的情况下捕获错误和输出,我建议使用子进程模块。

import subprocess

processToRun = "python callscript.py -i %s" % path
proc = subprocess.Popen (processToRun, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(proc.returncode)
  1. 如果您要调用 python 脚本,您应该考虑将其集成到您自己的 python 程序中。
  2. 否则,您应该使用 subprocess 模块,这在 python 文档中推荐,如 os.system. The documentation also suggests writing the replacement in this way substitute for os.system 所示。请参阅第 17.1.4.3 节。如何捕获异常。

我目前的解决方案:

import sys, getopt, os    
from subprocess import check_call, CalledProcessError


def scan_dir(path):

    fail_count = 0
    success = []
    failure = []

    temp_path = path
    print temp_path
    for file in os.listdir(path):
            temp_path += file
            if file.endswith(".txt"):
                    try:
                            check_call(["python", "callscript.py","-i", temp_path])
                            success.append(file)
                    except CalledProcessError as e:
                            print e.message
                            failure.append(file)
                            fail_count += 1
                            continue
            temp_path = path

    if fail_count > 0:
            f = open("log.txt", "w")
            print ("%d Errors occurred during conversion. Check log.txt for details" % fail_count)
            f.write("The following files were successfully converted:\n")
            for s in success:
                    f.write("\t-%s\n" % s)

            f.write("\n\nThe following files failed to be converted:\n")
            for a in failure:
                    f.write("\t-%s\n" % a)
            f.close()
    else:
            print "All files converted successfully!"


def usage():
    print "usage:  dostuff.py [hi:]\n \
          \t -h\t print usage\n \
          \t -i\t directory path\n"
    sys.exit(2)

def main(argv):

    if(len(argv) == 0):
            usage()

    path = ''

    try:
            opts, args = getopt.getopt(argv,"hi:",["path="])
    except getopt.GetoptError:
            usage()

    for opt, arg in opts:
            if opt == '-h':
                    usage()
elif opt in ("-i", "--ifile"):
                    path = arg
    if path.endswith('/') == False:
            path += '/'

    scan_dir(path)


if __name__ == "__main__":
    main(sys.argv[1:])