Designing a program entry point in python

The main file, designed to run everything, is now a mess of a dozen variables (which are global by default top-level control flow), a couple of structures and a medium-sized main loop. From other languages, I learned that globals are evil. I usually put all this in a class in one file and call only one method from the global control flow, for example:

def MyClass:
  def __init__(self):
    self.value1 = 1
    ....

 if __name__ == "__main__":
   #inspect sys.argv here
   MyClass().main_proc()

Do you consider this a plus project? Is there a way for pythons?

+4
source share
1 answer

Python does not force you to use OOP, for example, for example. Java or C #, so you don’t need to put things in classes unless there is a real benefit to you from this.

- IMHO. . - , . , .

:

main.py:

if __name__ == "__main__":
    import sys
    args = sys.argv[1:]
    if len(args) != 2:
        print("This script requires exactly two command-line arguments!")
        exit(1)

    import my_module
    exit_code = my_module.run(args) or 0
    exit(exit_code)
else:
    raise ImportError("Run this file directly, don't import it!")

my_module.py:

# initialization code to be run at import time goes here

def run(args):
    # do whatever you need to do
    print("Hello world!")
    print("You said <", args[0], "> and <", args[1], ">."

    # you may return an integer (1-255) as exit code if an error occurred,
    # else the default exit code is 0 (successful; no error)

! ( ) , , , , .

. , , , . , , .

( ) , , if __name__ == "__main__" .

+3

All Articles