name
In the code you are running, __ name __ ='__main __' Inside the imported file, __ name __ ='filename' is included By distinguishing this, you can see which file is running Therefore, you can create a mechanism that main () is not executed when the main file is called by another file.
b.py
def import_print_name():
return __name__
print(import_print_name())
main.py
import b
def main():
print("It will be the imported file name. In this case",b.import_print_name())
print(__name__)
if __name__ == '__main__':
main()
Execution result (execute main).
b
It will be the imported file name. In this case b
__main__
The above b is called at the time of import b
b.py
def import_print_name():
return __name__
if __name__=='__main__':
print(import_print_name())
main.py
import b
def main():
print("It will be the imported file name. In this case",b.import_print_name())
print(__name__)
if __name__ == '__main__':
main()
Execution result (execute main).
It will be the imported file name. In this case b
__main__
Recommended Posts