有没有办法缩进Python而不影响代码

时间:2015-01-19 18:28:50

标签: python maya pymel

我正在尝试在Maya中编写一个用户界面,并且它与多个级别的父级并且没有缩进令人难以置信地混淆。基本代码(没有任何功能)目前大约有400行,需要一段时间才能找到我需要的位。

例如,在没有注释的情况下使用以下代码:

#Earlier user interface

py.rowColumnLayout( numberOfColumns = 5 )
py.text( label="", width = 1 )
py.text( label="Column 1", enable = False, width = 250 )
py.text( label="", width = 1 )
py.text( label="Column 2" enable = False, width = 250 )
py.text( label="", width = 1 )

py.text( label="" )
py.rowColumnLayout( numberOfColumns = 4 )
py.text( label="   Input data:", align="left" )
py.text( label="" )
py.text( label="" )
py.text( label="" )
py.textField( text = "Text here" )
py.text( label="" )
py.text( label="" )
py.text( label="" )
py.setParent( ".." )

py.text( label="" )
py.rowColumnLayout( numberOfColumns = 4 )
py.rowColumnLayout( numberOfColumns = 5 )
py.radioButton( label = "Read file from path", width = 100 )
py.text( label="" )
py.button( label = "Browse" )
py.text( label="" )
py.button( label = "Validate" )
py.setParent( ".." )
py.text( label="" )
py.text( label="" )
py.text( label="" )
py.setParent( ".." )
py.setParent( ".." )

但是,这就是缩进的外观

py.rowColumnLayout( numberOfColumns = 5 )
    py.text( label="", width = 1 )
    py.text( label="Column 1", enable = False, width = 250 )
    py.text( label="", width = 1 )
    py.text( label="Column 2" enable = False, width = 250 )
    py.text( label="", width = 1 )

    py.text( label="" )
    py.rowColumnLayout( numberOfColumns = 4 )
        py.text( label="   Input data:", align="left" )
        py.text( label="" )
        py.text( label="" )
        py.text( label="" )
        py.textField( text = "Text here" )
        py.text( label="" )
        py.text( label="" )
        py.text( label="" )
        py.setParent( ".." )

    py.text( label="" )
    py.rowColumnLayout( numberOfColumns = 4 )
        py.rowColumnLayout( numberOfColumns = 5 )
            py.radioButton( label = "Read file from path", width = 100 )
            py.text( label="" )
            py.button( label = "Browse" )
            py.text( label="" )
            py.button( label = "Validate" )
            py.setParent( ".." )
        py.text( label="" )
        py.text( label="" )
        py.text( label="" )
        py.setParent( ".." )
    py.setParent( ".." )

有什么办法我可以用缩进写它但是让它在执行时忽略它们吗?我看到了一个问题,问你是否可以在没有缩进的情况下编写python,但我有点需要相反。

注意:某些py.*函数的输出值也需要分配给变量,因为布局需要先排序,所以还没有。

6 个答案:

答案 0 :(得分:6)

这是一个很好的用例,像我们这样的技术艺术家每天都会在Maya中构建UI。

对于基于PyMEL的UI:

这内置于PyMEL中。您不必创建上下文管理器。布局命令本身是上下文管理器。您只需在每个布局命令调用之前添加with关键字,如下所示:

# Do this when using PyMEL for your UI code
import pymel.core as pm

# ...

with pm.rowColumnLayout( numberOfColumns = 5 ):
    pm.text( label="", width = 1 )
    pm.text( label="Column 1", enable = False, width = 250 )
    pm.text( label="", width = 1 )
    pm.text( label="Column 2", enable = False, width = 250 )
    pm.text( label="", width = 1 )

    pm.text( label="" )

    with pm.rowColumnLayout( numberOfColumns = 4 ):
        pm.text( label="   Input data:", align="left" )
        pm.text( label="" )
        pm.text( label="" )
        pm.text( label="" )
        pm.textField( text = "Text here" )
        pm.text( label="" )
        pm.text( label="" )
        pm.text( label="" )        

    pm.text( label="" )
    with pm.rowColumnLayout( numberOfColumns = 4 ):
        with pm.rowColumnLayout( numberOfColumns = 5 ):
            pm.radioButton( label = "Read file from path", width = 100 )
            pm.text( label="" )
            pm.button( label = "Browse" )
            pm.text( label="" )
            pm.button( label = "Validate" )

        pm.text( label="" )
        pm.text( label="" )
        pm.text( label="" )

对于基于maya.cmds的UI:

一个快速的解决方案是创建一个虚拟上下文管理器。你可以做这样的事情

# Do this when using Maya's cmds for your UI code
import maya.cmds as cmds

# ...

from contextlib import contextmanager
@contextmanager
def neat_indent():
    # OPTIONAL: This is also an opportunity to do something before the block of code runs!
    try:
        # During this is where your indented block will execute
        # Leave it empty
        yield
    finally:
        # OPTIONAL: This is where you can write code that executes AFTER your indented block executes.
        pass

这样你的代码就不必改变太多了。只需在每个预期缩进的开头添加with关键字的上下文管理器功能!

cmds.rowColumnLayout( numberOfColumns = 5 )
with neat_indent():
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 1", enable = False, width = 250 )
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 2", enable = False, width = 250 )
    cmds.text( label="", width = 1 )

    cmds.text( label="" )

    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent():
        cmds.text( label="   Input data:", align="left" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.textField( text = "Text here" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.setParent( ".." )

    cmds.text( label="" )
    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent():
        cmds.rowColumnLayout( numberOfColumns = 5 )
        with neat_indent():
            cmds.radioButton( label = "Read file from path", width = 100 )
            cmds.text( label="" )
            cmds.button( label = "Browse" )
            cmds.text( label="" )
            cmds.button( label = "Validate" )
            cmds.setParent( ".." )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.setParent( ".." )
    cmds.setParent( ".." )

我们创建的上下文管理器neat_indent()也让您有机会编写包装缩进块的代码。这里的一个实际例子是,在每个缩进的最后,你发现自己正在编写py.setParent("..")。您可以将其放入上下文管理器的finally部分:

from contextlib import contextmanager
@contextmanager
def neat_indent(parent=None):
    # OPTIONAL: This is also an opportunity to do something before the block of code runs!
    try:
        # During this is where your indented block will execute
        # Leave it empty
        yield
    finally:
        # OPTIONAL: This is where you can write code that executes AFTER your indented block executes.
        if parent:
            cmds.setParent(parent)

您的代码现在更有意义了:

cmds.rowColumnLayout( numberOfColumns = 5 )
with neat_indent(".."):
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 1", enable = False, width = 250 )
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 2", enable = False, width = 250 )
    cmds.text( label="", width = 1 )

    cmds.text( label="" )

    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent(".."):
        cmds.text( label="   Input data:", align="left" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.textField( text = "Text here" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )        

    cmds.text( label="" )
    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent(".."):
        cmds.rowColumnLayout( numberOfColumns = 5 )
        with neat_indent(".."):
            cmds.radioButton( label = "Read file from path", width = 100 )
            cmds.text( label="" )
            cmds.button( label = "Browse" )
            cmds.text( label="" )
            cmds.button( label = "Validate" )

        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )

上下文管理器很强大。在这篇文章中,我使用了contextmanager标准库模块中的contextlib装饰器。您可以阅读有关此技术here的信息。一般为here with。{/ p>

此外,为了达到这个目的(其中一个目的),在Maya中进行UI开发更清洁,更多Pythonic @theodox创建了mGui模块。看看吧。

答案 1 :(得分:1)

您可以在执行代码之前预处理代码行,如图所示:

mycode = """\
    print "something"
        print "something else"
      print 42
    """

exec('\n'.join(line.lstrip() for line in mycode.splitlines()))

输出:

something
something else
42

它甚至可以被制成“一线”:

exec('\n'.join(line.lstrip() for line in """\
    print "something"
        print "something else"
      print 42
    """.splitlines()))

您可以通过以下方式将代码保存在单独的文件中(这样可以使编辑器对其进行语法处理):

档案mycode.py

print "something"
    print "something else"
  var = 42

单独文件版本:

with open('mycode.py') as code:
    exec(''.join(line.lstrip() for line in code))
print 'var:', var

输出:

something
something else
var: 42

警告:我应该指出,这些都会从每一行中删除所有缩进,这会弄乱任何遇到的多行Python代码(如if/else) - 这可能会限制其有用性取决于你正在做什么。

答案 2 :(得分:1)

@ Kartik的回答很好地涵盖了基础。我指出,通过允许上下文管理器在线声明布局(rowLayout,columnLayout等),你可以更多地清理布局代码,这使得它更容易:

class uiCtx(object):
   '''
   quickie layouthelper: automatically setParents after a layout is finished
   '''
   def __init__(self, uiClass, *args, **kwargs):
        self.Control = uiClass(*args, **kwargs)

    def __enter__(self):
        return self

    def __exit__(self, tb, val, traceback):
        cmds.setParent("..")

    def __repr__(self):
        return self.Control

会在遇到时调用maya.cmds布局函数,然后在缩进块的末尾关闭父级,这样就可以像在此片段中一样进行布局调用

    with uiCtx(cmds.rowLayout, **layout_options) as widget:
        self.Toggle = cmds.checkBox('', v = self.Module.enabled, cc = self._state_changed)
        with uiCtx(cmds.columnLayout, w=self.COLUMNS[1], cal='left') as details:
            cmds.text(l = self.ModuleKey, fn = "boldLabelFont")
            cmds.text(l = self.Module.path, fn = "smallObliqueLabelFont")
        cmds.button("edit",  c=self._edit)
        cmds.button("show", c=self._show)
    return widget

__repr__添加到uiCtx可让您将其视为像普通maya布局命令一样返回字符串,因此在该示例中,可以通常的方式查询“窗口小部件”。

整个事情是up on GitHub在上下文中看到它。正如Kartik还指出,mGui的形式有一个更精细的声明性UI选项,在实践中看起来像这样:

with gui.Window('window', title = 'fred') as example_window:
    with BindingContext() as bind_ctx:
        with VerticalForm('main') as main:
            Text(None, label = "The following items don't have vertex colors")
            lists.VerticalList('lister' ).Collection < bind() < bound  
            with HorizontalStretchForm('buttons'):
                Button('refresh', l='Refresh')
                Button('close', l='Close')

# show the window
example_window.show()

还有一些与maya布局相关的信息here

答案 3 :(得分:0)

创建另一个程序来解析并执行script.py

parse.py

text = open('script.py').readlines()
text = [i.strip() for i in text]

edit = open('new.py', 'w')
for line in text:
    edit.write(line + '\n')
edit.close()

execfile('new.py')

此文件创建一个将被执行的修改后的new.py

答案 4 :(得分:0)

我可以想到两种可能性,允许您直接编写代码而无需从文本中解析它(语法着色完整,没有临时文件)。

第一种方法是将真理加到每一行的开头,如上面建议的if True:,或者等效地,可能是这样的:

# ...

if 'level 1':  a = py.text( label="" )
if 'level 2':      b = py.rowColumnLayout( numberOfColumns = 4 )
if 'level 3':          c = py.rowColumnLayout( numberOfColumns = 5 )
if 'level 4':              d = py.radioButton( label = "Read file from path", width = 100 )

# ...

如果您不使用评估为False的字符串(例如''),您可以将这些字符串用作评论,以帮助您记住您的GUI的哪个部分。在任何给定的线上重建(用适当数量的空格填充,以确保事物仍然排成一行)。

第二个想法是创建一个包含callables及其参数的容器列表,然后按照你喜欢的方式格式化,然后在最后执行每一个:

objects = {}
commands = [

    # ...

    dict( name = 'spam', func = py.text, label="" ),
    dict( name = 'ham', func = py.rowColumnLayout, numberOfColumns = 4 ),
        dict( name = 'eggs', func = py.rowColumnLayout, numberOfColumns = 5 ),
            dict( name = 'beans', func = py.radioButton, label = "Read file from path", width = 100 ),

    # ...
]

for d in commands:
    objects[ d.pop( 'name' ) ] = d.pop( 'func' )( **d )

答案 5 :(得分:0)

使用声明式方法:

interface = [
  [py.rowColumnLayout, [], dict(numberOfColumns=5)],
     [py.text, [], dict(label="", width=1)],
     [py.text, [], dict(label="Column 1", enable=False, width=250)],
     ...
     [py.setParent, [".."], {}],
]    

for callable, args, kwargs in interface:
    callable(*args, **kwargs)

内部()[]缩进无关紧要,因此您可以根据需要自由组织这些行。