在__name__ =='__main__'中调用:在另一个模块中的某个模块中的一个模块中 [英] Calling if __name__ == '__main__': in one module from a function in another module
问题描述
我需要调用 if __name__ =='__main __'
,它调用一个模块中的几个类, Module 1
,在函数中, function1
,它在第二个模块的类中, Module 2
。
我不能在模块1中使用
。 def main()
code>而不是 if __name__ =='__main __'
,因为模块有几个类和函数连接到 Class_1 $ c $仅在
c> if __name__ =='__main __': print('我是:',__name __)
和<$ c $的
所以我的问题是如何从<$ c $从调用main:
? if __name__ =='__main __'
在 class_2() in
> Module 2 function1
中的c> Class_1()
第1单元
print('I am:',__name__)
$ b $ class class_1():
.... code ...
#调用模块中的所有内容:
if __name__ =='__main__':
Module 2
#if #_name__ =='__main__'from Module 1 should be called in function 1
$ b $ class Class_2():
.... code ..
def function1:
---调用main if __name__ =='__main__'from Module 1
对于你提出的问题,我能想到的最好的方法就是你希望在module1.py中定义的函数在你运行时运行调用module2.py。这可能是这样的: I need to call I can't use So my question is how I can call main: Module 1 Module 2
The For the question you asked, the best I could come up with is that you wanted a function defined in "module1.py" to run when you invoke "module2.py". That would be something like this:
这篇关于在__name__ =='__main__'中调用:在另一个模块中的某个模块中的一个模块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! if __name__ =='__main __'
主要用于制作一个python脚本可执行文件。例如,你定义了一个函数来执行某些操作,通过导入并运行它来使用它,但是当你使用 python module1.py $运行你的python脚本时,你也希望执行这个函数。 c $ c
### module1.py:
def main():
#做一些
...
if __name__ =='__main__':
main()
### module2.py:
from module1 import main main as main_from_module_one
$ b $ if if __name__ =='__main__':
main_from_module_one()#调用函数main在module1中定义
if __name__ == '__main__'
, that calls several classes in one module, Module 1
, in a function, function1
, that's in a class in a second module, Module 2
. def main()
- solution in Module 1
instead of if __name__ == '__main__'
, since the module has several classes and functions connected to Class_1
in Module 1
that only works with print('I am:', __name__)
and if __name__ == '__main__':
. if __name__ == '__main__'
from Class_1()
in function1
in Class_2()
in Module 2
?print('I am:', __name__)
class Class_1():
....code...
# calling everything in the module that
if __name__ == '__main__':
# if __name__ == '__main__' from Module 1 should be called in function 1
class Class_2():
.... code..
def function1:
--- calling main if __name__ == '__main__' from Module 1
if __name__ == '__main__'
is mainly used to make a single python script executable. For instance, you define a function that does something, you use it by importing it and running it, but you also want that function to be executed when you run your python script with python module1.py
.### module1.py:
def main():
# does something
...
if __name__ == '__main__':
main()
### module2.py:
from module1 import main as main_from_module_one
if __name__ == '__main__':
main_from_module_one() # calling function main defined in module1