0

I am trying to open an Excel file and to take the columns according to the names (headings). If it doesn't find those headings, I want the script to stop and display a message that the column was not found.

I first assign the current numbers to the columns with those names, and then I search for the name in the headings to make sure there were no columns inserted in between that will alter the column numbers. If the number is not the same, it will take whatever column number the name is in.

I have been trying to put an "else" under the "elif" and asking it to print an error and then I put a "break". The problem is that it doesn't stop the script if a column name is not found, it just takes the default assignment. I do understand why that break won't stop the whole script, but I don't know how to put it in order to stop it. The code is a bit more complex than just this, but I hope this will give a good understanding.

I also tried removing the default assignment but then it says that it can't find "i" so it gives me an error.

I would really appreciate some help.

Code:

colTPNumber = 2
colTDNumber = 3

rows = sheet.iter_rows(min_row=1, max_row=1)
firstRow = next(rows)
for i in firstRow:
    if str(i.value) == "TP":
        colTPNumber = i.column
    elif str(i.value) == "TD":
        colTDNumber = i.column
    else:
        print ("Column name not found")
        break
marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
TeoR
  • 5
  • 2
  • You're printing `column name not found` even if the columns were found. If column 1 contains `TP`, and column 2 contains `TD`, you'll print that error message when you process column 3. – Barmar Jun 11 '19 at 02:30
  • And if column 1 doesn't contain either of them, you break out of the loop and never look at the following columns. – Barmar Jun 11 '19 at 02:30
  • You can use `sys.exit()` to terminate the script. – Barmar Jun 11 '19 at 02:31
  • `break` exits the loop, not the whole program. Use `exit()` or `sys.exit()` (don't forget to `import sys` for the second option) to exit the program – marsnebulasoup Jun 11 '19 at 02:32
  • Use `sys.exit(1)`, or some other non-zero status, to indicate an error. Use `sys.exit(0)` for a normal, non-error exit. Be sure to `import sys`. – Tom Karzes Jun 11 '19 at 02:35

3 Answers3

0

Try using exit() instead of break. break ends a loop, but exit() actually exits your program.

marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
CygnusOlor
  • 94
  • 4
0

break exits the loop, not the whole program.

Use exit() or sys.exit() (don't forget to import sys for the second option) to exit the program

Example:

import sys #unnessary if you're using exit() only

colTPNumber = 2
colTDNumber = 3

rows = sheet.iter_rows(min_row=1, max_row=1)
firstRow = next(rows)
for i in firstRow:
    if str(i.value) == "TP":
        colTPNumber = i.column
    elif str(i.value) == "TD":
        colTDNumber = i.column
    else:
        print ("Column name not found")
        #break
        sys.exit()
        #OR
        exit()

Some more info:

You can also use quit()

  • quit() raises the SystemExit exception behind the scenes.

Furthermore, if you print it, it will give a message:

>>> print (quit) 
Use quit() or Ctrl-Z plus Return to exit 

This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  • exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

Furthermore, it too gives a message when printed:

>>> print (exit) 
Use exit() or Ctrl-Z plus Return to exit 

However, like quitexit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  • sys.exit raises the SystemExit exception in the background. This means that it is the same as quit and exit in that respect.

Unlike those two however, sys.exit() is considered good to use in production code. This is because the sys module will always be there.

  • os._exit exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios.

So, if you want to exit a program normally, go with the third method: sys.exit.

Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you


Adapted from: https://www.edureka.co/community/16988/python-exit-commands-why-so-many-and-when-should-each-be-used


More info on sys.exit():

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Changed in version 3.6: If an error occurs in the cleanup after the Python interpreter has caught SystemExit (such as an error flushing buffered data in the standard streams), the exit status is changed to 120.


From https://docs.python.org/3/library/sys.html

marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
0

Give the variables invalid default values, so you can check them after the loop.

Then you can call exit() if they're not set correctly, this will terminate the entire script.

colTPNumber = None
colTDNumber = None

rows = sheet.iter_rows(min_row=1, max_row=1)
firstRow = next(rows)
for i in firstRow:
    if str(i.value) == "TP":
        colTPNumber = i.column
    elif str(i.value) == "TD":
        colTDNumber = i.column
if colTPNumber is None or colTDNumber is None:
    print("Column name not found")
    exit(1)

See Terminating a Python script

Barmar
  • 741,623
  • 53
  • 500
  • 612