NameError: name '_name_' is not defined

Cin Sb Sangpi picture Cin Sb Sangpi · Aug 12, 2015 · Viewed 36.3k times · Source

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 -

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()

Answer

Anand S Kumar picture Anand S Kumar · Aug 12, 2015

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 -

if __name__=='__main__':