[英]ImportError: cannot import X from the file that has if __name__ == “__main__”. Any solutions without delete if __name__ == “__main__”?
I have 2 files n1711_001_insilico
and n1711_002_insilico
in the same folder. 我在同一文件夹中有2个文件
n1711_001_insilico
和n1711_002_insilico
。 I want two variables ( mzdf
which is <class 'pandas.core.frame.DataFrame'>
, and charge
is 'int'
) from the first file so I do import
at the top of the second file: 我想要第一个文件中的两个变量(
mzdf
是<class 'pandas.core.frame.DataFrame'>
,而charge
是'int'
),所以我要在第二个文件的顶部import
:
import numpy as np
import pandas as pd
from n1711_001_insilico import mzdf, charge
I got ImportError: cannot import name mzdf
(as well as for charge
). 我收到
ImportError: cannot import name mzdf
(以及charge
)。 In the first file, I explicitly return both mzdf
and charge
from the function and call them like this: 在第一个文件中,我从该函数中显式返回
mzdf
和charge
,并像这样调用它们:
if __name__ == "__main__":
mzdf, charge = CALC(peptides_report, aa_dict, charge_from=1, charge_to=6)
Update: from the comment I now know the issue comes from if __name__ == "__main__":
in the first file. 更新:从注释中,我现在知道问题来自第一个文件中的
if __name__ == "__main__":
。 Any ways that I can fix this without deleting if __name__ == "__main__"
? if __name__ == "__main__"
,我可以在不删除的情况下解决此问题的任何方法?
In the file you are trying to import, you have this statement: 在您要导入的文件中,您具有以下语句:
if __name__ == "__main__":
mzdf, charge = CALC(peptides_report, aa_dict, charge_from=1, charge_to=6)
This means that only if the file is directly executed in the command line, for example with python n1711_001_insilico.py
will the command CALC
actually run and be executed, and this is the function that is setting the two variables mzdf
and charge
. 这意味着只有在命令行中直接执行文件(例如,使用
python n1711_001_insilico.py
时, CALC
命令才会实际运行并执行,这是设置两个变量mzdf
和charge
的函数。
In other words, only when you run the file directly with python n1711_001_insilico.py
do these two variables exist, when you import it, Python will not run that function. 换句话说,只有当您直接使用
python n1711_001_insilico.py
运行文件时,这两个变量python n1711_001_insilico.py
存在,而在导入文件时,Python将不会运行该函数。
This is by design; 这是设计使然; once you import the file, the variable
__name__
points to the name of the file, so the condition fails. 导入文件后,变量
__name__
指向文件名,因此条件失败。
Now, to solve this problem you will have to run the CALC
function when you import the file, and get your own copy of the result: 现在,要解决此问题,您将必须在导入文件时运行
CALC
函数,并获得自己的结果副本:
import numpy as np
import pandas as pd
from n1711_001_insilico import peptides_report, aa_dict, CALC
mzdf, charge = CALC(peptides_report, aa_dict, charge_form=1, charge_to=6)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.