Python - 枚举

时间:2016-02-11 18:32:16

标签: python arrays deep-copy pyobjc

错误:

Traceback (most recent call last):
  File "<string>", line 10, in <module>
  File "/Users/georg/Programmierung/Glyphs/Glyphs/Glyphs/Scripts/GlyphsApp.py", line 59, in __iter__
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_convenience.py", line 589, in enumeratorGenerator
    yield container_unwrap(anEnumerator.nextObject(), StopIteration)
objc.error: NSGenericException - *** Collection <__NSArrayM: 0x7f9906245480> was mutated while being enumerated.

我知道发生此错误是因为我试图从阵列中删除对象,同时还要枚举这些对象。但我不知道如何解决它。我对面向对象的编程很新,并且限制自己编写脚本。

我在网上搜索它似乎解决了错误,我必须在删除它之前复制数组。当我想通过deepcopy复制数组时

import copy
pathcopy = copy.deepcopy(thisLayer.paths)

for path in thisLayer.paths:之前

但在这种情况下,我收到以下错误:

Cannot pickle Objective-C objects

通常程序在第一个字形后崩溃。澄清一下:我使用的是Typephing软件Glyphsapp。

以下是代码:

# loops through every Glyph and deletes every path with nodes on the left half
    for myGlyph in Glyphs.font.glyphs: 
        glname = myGlyph.name   
        thisLayer = Glyphs.font.glyphs[glname].layers[1]
        middle = thisLayer.bounds.size.width/2+thisLayer.LSB
        thisGlyph = thisLayer.parent

        for path in thisLayer.paths:    # this is where the code crashes
            for thisNode in path.nodes:
                if thisNode.position.x < middle:
                    #print thisNode.position.x
                    try:
                        thisLayer = path.parent()
                    except Exception as e:
                        thisLayer = path.parent
                    try:
                        thisLayer.removePath_ ( thisNode.parent() )
                    except AttributeError:
                         pass

提前谢谢

1 个答案:

答案 0 :(得分:0)

非常感谢Andreas,

在您的帮助下,我能够修复我的代码: - )

结果如下:

for myGlyph in Glyphs.font.glyphs:
    glname = myGlyph.name   
    thisLayer = Glyphs.font.glyphs[glname].layers[1]
    middle = thisLayer.bounds.size.width/2+thisLayer.LSB
    thisGlyph = thisLayer.parent

    for path in thisLayer.paths:    
        for thisNode in path.nodes:
            if thisNode.position.x < middle:
                nodeList = []
                nodeList.append(thisNode.parent())
    nLCopy = nodeList[:]
    for ncontainer in nLCopy:
        thisLayer.removePath_ ( ncontainer )