Continuing script after failure on os.system call python -
i have script have written scan directory of text files , if finds them, creates system call run script on txt file. still working on couple little bugs causes of system calls fail. like, however, not kill script. informed of error move on life. seems successful call returns 0 while call resulted in error returns n. tried compare result 0 never gets far. suggestions on how can accomplish this??
import sys, getopt, os def main(argv): def scan_dir(path): temp_path = path print temp_path 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() 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:])
you should using subprocess module in particular check_call, catching calledprocesserror
raised non-zero exit status:
subprocess import check_call,calledprocesserror try: check_call(["python", "callscript.py", "-i",path]) except calledprocesserror e: print e.message
not easy follow code, suggest not nesting other functions in main. use glob find txt files:
from glob import glob def scan_dir(path): files = (os.path.join(path,f) f in glob(os.path.join(path,"*.txt"))) fle in files: try: check_call(["python", "callscript.py", "-i", fle]) except calledprocesserror 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() opt, arg in opts: if opt == '-h': usage() elif opt in ("-i", "--ipath"): path = arg if not path.endswith('/'): path += '/' scan_dir(path)
Comments
Post a Comment