Using a module ' s __name__
Example? 8.2.? Using a module ' s __name__
#!/usr/bin/python# Filename:using_name.py' __main__ ': ' This program wasbeing run by itself 'else:' I Am being imported from another module '
Output
$ python using_name.pythis program was being run by itself$ python>>> import Using_namei am being imported from an Other module>>>
How It Works
Every Python module has it's __name__ defined and if this ‘__main__‘ are, it implies that the module was being run standalone by the User and we can do corresponding appropriate actions.
# Threading exampleimport time, threaddef myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime)if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
And what does it *args mean here?
When the Python parser reads a source file, it executes all the code. Some special variables are defined before executing the code. For example, if the parser is running a module (source file) as the main program, it will __name__ set the variable to "__main__" . If you just introduce other modules, __name__ The variable will be set to the module's name.
Suppose the following is your script, let's do it as the main program:
python threading_example.py
When a special variable is set, it executes the import statement and loads the modules. When a snippet def is encountered, it creates a function object and creates a myfunction pointer to the function object. Next reads the if statement and checks to see if it is __name__ equal "__main__" , If it is, he will execute the code snippet.
The reason for this is that sometimes you need to write a module that can be executed directly, but also can be used as a module to import into other modules. By checking if it is the main function, you can make your code execute only when it is running as the main program, but not when others call the function in your module.
if __name__ = = ' __main__ ' in Python: