Script doesn't execute when wrapped inside of a function

Question:

When I execute the script below with python3 ocr-test.py, it runs correctly:

from PIL import Image
import pytesseract
# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'/opt/homebrew/bin/tesseract'
# Simple image to string
print(pytesseract.image_to_string(Image.open('receipt1.jpg')))

However, when I excute the below script with python3 ocr-test.py process, the process/function does not get called and nothing happens:

from PIL import Image
import pytesseract
def process():
   # If you don't have tesseract executable in your PATH, include the following:
   pytesseract.pytesseract.tesseract_cmd = r'/opt/homebrew/bin/tesseract'
   # Simple image to string
   print(pytesseract.image_to_string(Image.open('receipt1.jpg')))

Why is this (not) happening?

Asked By: reallymemorable

||

Answers:

Try to add the following code at the very end of your file:

if __name__ == "__main__":
    process()

The reason that process does not execute is because it is probably not called in your file. I have not seen anyone calling a function from command line before, and I do not think it is possible, except for running something like:

python -c "from ocr-test import process;process()" 

but that is not common practice or recommended for that matter. Id stick with the first solution, but its up to you.

Answered By: no_modules

you need to add

if __name__ == '__main__':
    globals()[sys.argv[1]]()

to the bottom of the file.

as explained here.

Answered By: Arthur Caccavo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.