Skip to main content
 首页 » 编程设计

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

2024年10月25日13开发

我编写了一个脚本来扫描文本文件目录,如果找到它们,它会创建一个系统调用来在 txt 文件上运行脚本。我仍在处理一些导致我的一些系统调用失败的小错误。但是,我希望这不会杀死我的脚本。我只想被告知错误,然后继续我的生活。似乎任何成功的调用都会返回 0,而任何导致错误的调用都会返回 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:]) 

请您参考如下方法:

您应该特别使用子流程模块 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)