Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the Python equivalent of the Main method in Java, C, C++ & C#?

new to Python, coming from Java (& Android) & C,C++,C# background. Looking for similarities basically. What's the Entry point of a python project? like the Main method in other languages. A project with multiple .py scripts, how do I set an entry point?

like image 482
Mujtaba Nowshad Avatar asked Feb 23 '15 17:02

Mujtaba Nowshad


3 Answers

Simple script

Basically the code in a Python module just runs. For a really simple program you could create a Python file hi.py with the following contents:

print('Hi ' + raw_input('What is your name?\n'))

This can be run using:

$ python hi.py
What is your name?
Remco
Hi Remco

Making it executable

In systems which support this you could add a shebang and make the file executable. The hi.py now looks like this:

#!/usr/bin/env python
print('Hi ' + raw_input('What is your name?\n'))

Then from a terminal run

$ chmod +x hi.py
$ ./hi.py
What is your name?
Remco
Hi Remco

__main__

You may want to split the logic, so it can be used in other modules as well. In that case you don't want to run all code in the module. The main module which was run is named __main__. This is typically what you use for a simple script.

hi.py:

#!/usr/bin/env python
def get_name():
    return raw_input('What is your name?\n')


if __name__ == '__main__':
    print('Hi ' + get_name())

bye.py:

#!/usr/bin/env python
import hi


if __name__ == '__main__':
    print('Bye ' + hi.get_name())

entry points

The project is now getting serious. It should be properly packaged so it can be distributed and installed by others. For this a setup.py must be created. The project now has the following filestructure:

|- bye.py
|- hi.py
`- setup.py

entry points are functions, so we will need to put the main functionality in functions. Let's name both functions main.

hi.py:

#!/usr/bin/env python
def get_name():
    return raw_input('What is your name?\n')


def main():
    print('Hi ' + get_name())

bye.py:

#!/usr/bin/env python
import hi


def main()
    print('Bye ' + hi.get_name())

setup.py:

#!/usr/bin/env python
from setuptools import setup


setup(
    name='greeter',
    version='0.0.0',
    py_modules=['hi', 'bye'],
    entry_points={
        'console_scripts': [
            'hi = hi:main',
            'bye = bye:main'
        ]
    })

I will not go into details about python packaging. The point is that the entry points refer to the main functions of the hi and bye modules. Similarly 'gui_scripts' can be specified.

The next steps following should be used from within a virtualenv.

The package can now be installed by running:

$ python setup.py install

You can now simply access the main function from the command line:

$ hi
What is your name?
Remco
Hi Remco

This is typically what you use when creating a package you want to distribute.

scripts

Another way is to specify scripts in setup.py. This allows to run the Python scripts as regular scripts like in the beginning. To implement this, just run the main function from within that file and specify it as a script in setup.py.

hi.py:

#!/usr/bin/env python
def get_name():
    return raw_input('What is your name?\n')


def main():
    print('Hi ' + get_name())


if __name__ == '__main__':
    main()

bye.py: #!/usr/bin/env python import hi

def main():
    print('Bye ' + hi.get_name())


if __name__ == '__main__':
    main()

setup.py:

#!/usr/bin/env python
from setuptools import setup


setup(
    name='greeter',
    version='0.0.0',
    py_modules=['hi', 'bye'],
    entry_points={
        'console_scripts': [
            'hi = hi:main',
            'bye = bye:main'
        ]
    },
    scripts=['hi.py', 'bye.py'])

Reinstall the package. There are now 3 ways to run hi and bye:

By directly calling the file:

$ python hi.py

From anywhere using the entry point:

$ hi

From anywhere using the setuptools scripts:

$ hi.py

Note that scripts may also refer to non-python scripts.

like image 139
Remco Haszing Avatar answered Oct 29 '22 19:10

Remco Haszing


The Python equivalent for the C main function could be called your main module.

Normally you have one module, you start Python with, e.g.:

python main.py

When you start this module, all coding that is on module level will be executed. This coding is equivalent to the main function in C. So you don't have a main function, but a main module (which you can name as you like).

If you want to have a main function, just add:

if __name__ == '__main__':
   main()

inside your main module (preferably at the end) and define the main function in your module. The if statement is to prevent the execution of the code, when the module is not used as main module (it is imported from a different module).

But, one thing you must be aware of: In C, only the main function is called implicitly by starting the program. Python is totally different. All module level coding of all modules that are used in the program is executed at start of the program.

like image 5
Juergen Avatar answered Oct 29 '22 19:10

Juergen


To quote from this thread:

if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python myscript.py.

I wouldn't say it is exactly the same thing. However it is similar, but not mandatory.

Example code:

def FunctionToRunProgram:
    # Do amazing things

if __name__ == "__main__":
    FunctionToRunProgram()

If the name of this program was called DoAmazingThings.py when you run python DoAmazingThings.py in a terminal, or whatever you decide to use, it will always start with the function under that if statement.

like image 3
Shawnic Hedgehog Avatar answered Oct 29 '22 21:10

Shawnic Hedgehog