$ python test.py. When you execute a Python script, it is treated as the main and its __name__ attribute is set to "__main__". However, it may seem confusing at times. 1. 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__.
def main (): pass . If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”. len(sys.argv) is the number of command-line arguments. The following are code examples for showing how to use __main__.__file__().They are from open source Python projects. For the second scenario we use some hackish syntax like . link brightness_4 code. If this file is being imported from another module, __name__ will be set to the module’s name.
So, what is going on here? play_arrow.
Example 2
$ 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. 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__. You can vote up the examples you like or vote down the ones you don't like. A module is a file containing Python definitions and statements. Every module in python has a special attribute called __name__. Now let’s look at a slightly different example.
Here is the output that you will see on the screen. Whenever Python runs a file, it sets up a few special variables and ‘__name__’ is one of those. Python provides a getopt module that helps you parse command-line options and arguments. As you can see above the value of the __name__ variable is of string data type and equals to ___main__. filter_none. $ python3 test.py __name__ in test.py is set to __main__. If this file is being imported from another module, __name__ will be set to … Below are the two key features of __name__ variable. From this, we can conclude that in this example, the variable __name__ was set to the string value __main__. __name__ is a built-in variable which evaluates to the name of the current module. filter_none. The value of __name__ attribute is set to '__main__' when module run as main program.
if __name__ == '__main__': main() chevron_right. Before executing the code, it will define a few special variables.