solarisman
solarisman

Reputation: 256

Python: How to use a third-party library

I am feeling completely stupid. I am a Python beginner and would like to use third-party libraries, such as dxfgrabber.

I have played with the following, which is given in the help section, but I don't know further:

import dxfgrabber

dxf = dxfgrabber.readfile("1.dxf")

print("DXF version: {}".format(dxf.dxfversion))

header_var_count = len(dxf.header) 

layer_count = len(dxf.layers) 

entity_count = len(dxf.entities) 

print layer_count

print entity_count

print dxf.layers

output so far is:

DXF version: AC1009

6

2

<dxfgrabber.layers.LayerTable object at 0x10f42b590>

my questions:

It seems like this library should be ready to use, but maybe for people with more knowledge about Python than me.

Upvotes: 0

Views: 1433

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121844

From your last print you can see that you have a LayerTable object; the documentation for LayerTable says there should be a .layernames() method, as well as a .get(layername) method to get at individual layers.

It also states that you can iterate over the object (there is a .__iter__() method), so you can use for layer in dxf.layers: to get at individual Layer objects.

The same information is available for the EntitySection object, it too has an __iter__() method to loop over the 2 entities defined. The documentation then list the entity types that you could encounter, with further documentation on how to access their information.

Unfortunately, there is at least one bug in the library; the LayerTable.__iter__() method doesn't return the correct type of object. A quick glance at the source code shows that other __iter__() methods do return correct items.

You can use

for layername in dxf.layers.layernames():
    layer = dxf.layers.get(layername)

instead for now, or call the __iter__() method directly:

for layer in dxf.layers.__iter__():
    # ..

I've filed a pull request to fix the issue.

Upvotes: 1

elyase
elyase

Reputation: 40963

Try for example:

for layer in dxf.layers:
    print layer.name, layer.color

Explanation:

The output of your last print command indicates that dxf.layers is a LayerTable object. In the documentation you can see that a LayerTable object has a property:

LayerTable.__iter__()
Iterate over all layers, yields Layer objects.

This means that it can be iterated in a for loop or whatever construction that takes an iterable. In the case of entities you can do something like this:

all_layer_0_entities = [entity for entity in dwg.entities if entity.layer == '0']

Here applies the same principle, the object dwg.entities is being iterated yielding an entity in each iteration.

You are right that the documentation could use more examples. See this post for some of that.

Upvotes: 1

Related Questions