If this file is being imported from another module, __name__ will be set to … Now let’s look at a slightly different example. 1. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”.

filter_none. Python provides a getopt module that helps you parse command-line options and arguments. You can vote up the examples you like or vote down the ones you don't like. Python files (single file structure) which can be run directly by command line ; In the first scenario when we try to import it as a module __init__.py comes into play. $ python test.py arg1 arg2 arg3 The Python sys module provides access to any command-line arguments via the sys.argv.This serves two purposes − sys.argv is the list of command-line arguments. A module is a file containing Python definitions and statements.

__main__. def main (): pass . Every module in python has a special attribute called __name__.

if __name__ == '__main__': main() chevron_right. len(sys.argv) is the number of command-line arguments. From this, we can conclude that in this example, the variable __name__ was set to the string value __main__. As you can see above the value of the __name__ variable is of string data type and equals to ___main__.
Whenever Python runs a file, it sets up a few special variables and ‘__name__’ is one of those. Using the if __name__ == “__main__” statement is quite regular in Python files. __name__ is a built-in variable which evaluates to the name of the current module. When you execute a Python script, it is treated as the main and its __name__ attribute is set to "__main__". The value of __name__ attribute is set to '__main__' when module run as main program.
$ python3 test.py __name__ in test.py is set to __main__. So, what is going on here? If this file is being imported from another module, __name__ will be set to the module’s name. It will output a string ‘__main__’. Example 2 Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value __main__. edit close. $ python test.py. The following are code examples for showing how to use __main__.__file__().They are from open source Python projects. Here is the output that you will see on the screen. filter_none. When you run any well-written stand-alone python script which is not referring to any other script, the value of __name__ variable is equal to __main__. Below are the two key features of __name__ variable. link brightness_4 code. play_arrow. However, it may seem confusing at times. For the second scenario we use some hackish syntax like .