Python NameError: 名称 '_name_' 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31956594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameError: name '_name_' is not defined
提问by Cin Sb Sangpi
I have gone through the similar question in stackoverflow but couldn't find the answer close to my problem. In the code below the 3 line before the last line is giving Error -
我在 stackoverflow 中遇到了类似的问题,但找不到接近我的问题的答案。在最后一行之前的第 3 行下方的代码中,给出错误 -
NameError: name '_name_' is not defined
NameError: name '_name_' is not defined
I have copied the below code from the University Lab guide instruction. Not really sure, how the code is working. We were just told to copy and paste for this lab and see the result. However, We have to type all the code into the command line and I am stuck. How could I fix this error in the code?
我从大学实验室指南中复制了以下代码。不太确定,代码是如何工作的。我们只是被告知复制和粘贴此实验室并查看结果。但是,我们必须在命令行中输入所有代码,我被卡住了。我怎样才能修复代码中的这个错误?
#!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel
class SingleSwitchTopo(Topo):
“Single switch connected to n hosts.”
def_init_(self,n=2,**opts):
#initialize topology and default options
Topo._init_(self,**opts)
switch=self.addSwitch(‘s1')
#Python's range(N) generates 0..N-1
for h in range(n):
host=self.addHost(‘h%s'%(h+1))
self.addLink(host,switch)
def simpleTest():
“Create and test a simple network”
topo=SingleSwitchTopo(n=4)
net=Mininet(topo)
net.start
print “Dumping host connections”
dumpNodeConnections(net.hosts)
print “Testing network connectivity”
net.pingAll()
net.stop()
if _name_=='_main_':
#Tell mininet to print useful information
setLogLevel(‘info')
simpleTest()
采纳答案by Anand S Kumar
The issue is in line -
问题是一致的 -
if _name_=='_main_':
My guess is you have that line so that the code only runs when run as a script, and not when importing, if so, you need double underscore on both sides of name
as well as main
. And looks like the quotes are wrong, you need to use '
. Example -
我的猜测是你有行,以便在运行时作为脚本,而不是导入时,如果是的话,你需要在两侧双下划线的代码只运行name
以及main
。看起来引号是错误的,您需要使用'
. 例子 -
if __name__=='__main__':
回答by Cin Sb Sangpi
In the
在里面
if _name_=='_main_':
you haven't written the code by using double underscore, it should be like following
您还没有使用双下划线编写代码,它应该如下所示
if __name__=='__main__':
thank you for above answer, they pointed the error for me yet it was not clear. I have make it clear by answering my own question.
感谢您的上述回答,他们为我指出了错误,但尚不清楚。我已经通过回答我自己的问题说清楚了。
回答by zxvn
You need two underscores instead of one:
您需要两个下划线而不是一个:
if __name__ == "__main__"
if __name__ == "__main__"
Python executes that directly. If its left out it will execute all the code from the 0th level of indention.
Python直接执行。如果它被遗漏,它将执行第 0 级缩进的所有代码。