Home > Net >  Continue program even after assert fails
Continue program even after assert fails

Time:07-09

I want to continue even after the assert statement fails. Instead of saying "File not found" I would like to ignore it and continue my program. I am unable to figure out the syntax.

Overview of the script and problem faced : This script is used for downloading pdf from urls which were written in a txt file. I had used assert to stop the program if the file wasn't found. It worked fine when all the urls in that txt file were working. The problem arose when there was a link which was dead and I didn't want the program to stop but instead continue to next link.

assert os.path.exists(of), "File not found at, "  str(of)

Program snippet :

for line in url_file:
  stripped_line = line.split(',')
  list_of_urls.append(stripped_line[2] stripped_line[1])
  driver.get(stripped_line[2] stripped_line[1])
  time.sleep(2)
  
  of = download_dir "/" stripped_line[3] ".pdf"
  fn = download_dir "/" stripped_line[0] ".pdf"

  try: 
    assert os.path.exists(of), "File not found at, "  str(of)
  except AssertionError: 
    pass

  move(of, fn)
  fns.append(stripped_line[0])
  ofns.append(stripped_line[3])
  status_file.write(stripped_line[0] ",File Downloaded\n")

url_file.close()
status_file.close()
driver.quit()

CodePudding user response:

If you really want to use assert you can just us a try: except: block to catch the error thrown if the assertion is not True

try: 
    assert os.path.exists(of), "File not found at, "  str(of)
except AssertionError: 
    pass

However if your goal is just to print an error message if the file does not exist you can do:

if not os.path.exists(of):
    print("File not found at, "  str(of))

CodePudding user response:

    if os.path.exists(of):
        move(of, fn)
        fns.append(stripped_line[0])
        ofns.append(stripped_line[3])
 
  • Related