Python NameError: name '__main__' 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21867009/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:46:33  来源:igfitidea点击:

NameError: name '__main__' is not defined

pythonmainmaya

提问by arvidurs

I have been reading here, but I couldnt find any solution online to solve my problem..I think I have the indentation right, but I still get the Name Error..Can someone help me out please. This script should run a new panel in maya, which works kind of, but the error is really annoying.

我一直在这里阅读,但我无法在网上找到任何解决方案来解决我的问题。这个脚本应该在 Maya 中运行一个新面板,它可以工作,但错误真的很烦人。

class PanelWindow( object ):
    def __init__( self, name, title, namespace=__name__ ):
        self.__name__ = name
        self._title = title
        self.instance = str(namespace) + '.' + self.__name__

        if not pm.scriptedPanelType(self.__name__, q = True, ex = True):
            pm.scriptedPanelType(self.__name__, u = True)

        jobCmd = 'python(\\"%s._setup()\\")' % self.instance
        job = "scriptJob -replacePrevious -parent \"%s\" -event \"SceneOpened\" \"%s\";" % ( self.__name__, jobCmd )
        mel.eval(job)

        pm.scriptedPanelType( self.__name__, e = True,
                       unique=True,
                       createCallback = 'python("%s._createCallback()")' % self.instance,
                       initCallback = 'python("%s._initCallback()"  )' % self.instance,
                       addCallback = 'python("%s._addCallback()"   )' % self.instance,
                       removeCallback = 'python("%s._removeCallback()")' % self.instance,
                       deleteCallback = 'python("%s._deleteCallback()")' % self.instance,
                       saveStateCallback = 'python("%s._deleteCallback()")' % self.instance
                        )


    def _setup(self):
        """Command to be call for new scene"""
        panelName = pm.sceneUIReplacement( getNextScriptedPanel=(self.__name__, self._title) )
        if panelName == '':
            try:
                panelName = pm.scriptedPanel( mbv=1, unParent=True, type=self.__name__, label=self._title )
            except:
                pass
        else:
            try:
                label = panel( self.__name__, query=True, label=True )
                pm.scriptedPanel( self.__name__, edit=True,  label=self._title )
            except:
                pass
    def _addCallback(self):
        """Create UI and parent any editors."""
        print 'ADD CALLBACK'
    def show( self ):        
        mel.eval('tearOffPanel "%s" %s true;' % (self._title, self.__name__) )


global test
test = PanelWindow('myName', 'Light')

test.show()


# NameError: name '__main__' is not defined # 
# Error: line 1: name '__main__' is not defined
# Traceback (most recent call last):
#   File "<maya console>", line 1, in <module>
# NameError: name '__main__' is not defined # 

采纳答案by Shannon Hochkins

Your problem was a few things, I've only included a few basic sections of the code as the rest wasn't needed.

您的问题是几件事,我只包含了代码的几个基本部分,因为其余部分不需要。

Problem one was __name__, if this were quoted, we wouldn't have a problem, seeing as it's just a name and not anything special, I'm just going to rename this to name.

问题一是__name__,如果引用它,我们就不会有问题,因为它只是一个名称而不是任何特殊的东西,我只是将它重命名为name.

Problem two was duplicate names on panels/panelTypes. IE:

问题二是面板/面板类型上的重复名称。IE:

pm.scriptedPanelType(self.__name__, u = True)
pm.scriptedPanel( self.__name__, edit=True,  label=self._title )

Maya didn't like that both the panelType and the panel had the same names.

Maya 不喜欢 panelType 和面板具有相同的名称。

So:

所以:

import maya.cmds as cmds
import pymel.core as pm
import maya.mel as mel

class PanelWindow( object ):
    def __init__(self, name, title):

        self._name = name
        self._title = title
        self.panelTypeName = self._name + "Type"



        if not pm.scriptedPanelType(self.panelTypeName, query=True, exists=True):
            pm.scriptedPanelType(self.panelTypeName, unique=True)

        if not pm.scriptedPanel(self._title, query=True, exists=True):
            ## Only allows one instance
            pm.scriptedPanel(self._title, menuBarVisible=1, unParent=True, type=self.panelTypeName, label=self._title )

    def _addCallback(self):
        """Create UI and parent any editors."""
        print 'ADD CALLBACK'        


    def show( self ):  
        mel.eval('tearOffPanel "%s" "%s" true;' % (self._title, self._name) )  



PanelWindow('lightControlType1', 'lightControl').show()

回答by Peter Gibson

When executing Python scripts, the Python interpreter sets a variable called __name__to be the string value "__main__"for the module being executed (normally this variable contains the module name).

在执行 Python 脚本时,Python 解释器会设置一个变量,称为正在执行的模块__name__的字符串值"__main__"(通常这个变量包含模块名称)。

It is common to check the value of this variable to see if your module is being imported for use as a library, or if it is being executed directly. So you often see this block of code at the end of modules:

检查这个变量的值是很常见的,看看你的模块是否被导入用作库,或者它是否被直接执行。所以你经常会在模块的末尾看到这段代码:

if __name__ == '__main__':
    # do stuff

I suspect you have left the string quotes off of '__main__'which gives the NameError you're seeing

我怀疑你已经离开了字符串引号,'__main__'它给出了你看到的 NameError

>>> if __name__ == __main__:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__main__' is not defined