0

The following code is not padding strings correctly

    for pre, fill, node in anytree.RenderTree(tree):

        prefix = ("{pre_print}{node_print}".format(pre_print=pre.encode('utf-8'), node_print=node.name)).ljust(120, '-')
        f.write("{pref}> {status}".format(pref=prefix, status=node.status.message()))
        f.write("\n")

Some of the output I'm getting is (I shortened the line padding for readability):

├── modelo_srtm_30_nuevo----------------------------------> No cumple regla
├── modelos_externos--------------------------------------> Ok
│   ├── .snapshot---------------------------------------> No cumple regla
│   ├── 2017 - Aguas Blancas----------------------------> No cumple regla

When the pre changes, the line is no longer the length it should be.

EDIT: the following codes demonstrates the problem, creating a sample tree and printing it:

import anytree


root = anytree.Node(name="root")
child_1 = anytree.Node(name="child_1", parent=root)
grandchild_11 = anytree.Node(name="grandchild_11", parent=child_1)
child_2 = anytree.Node(name="child_2", parent=root)
grandchild_21 = anytree.Node(name="grandchild_21", parent=child_2)
child_3 = anytree.Node(name="child_3", parent=root)
grandchild_31 = anytree.Node(name="grandchild_31", parent=child_3)

filename = "test_tree.txt"

with open(filename, "wt") as f:

    for pre, fill, node in anytree.RenderTree(root):

        prefix = ("{pre_print}{node_print}".format(pre_print=pre.encode('utf-8'), node_print=node.name)).ljust(40, '-')
        f.write("{pref}> {status}".format(pref=prefix, status="testing..."))
        f.write("\n")
MPA95
  • 175
  • 2
  • 11

1 Answers1

2

As Antti hints, justifying after encoding won't give very fruitful results. Try justifying first and then encoding:

with open(filename, "wt") as f:
    for pre, fill, node in anytree.RenderTree(root):
        prefix = (u"{pre_print}{node_print}".format(pre_print=pre, node_print=node.name)).ljust(40, '-').encode("utf-8")
        f.write("{pref}> {status}".format(pref=prefix, status="testing..."))
        f.write("\n")

Result:

root------------------------------------> testing...
├── child_1-----------------------------> testing...
│   └── grandchild_11-------------------> testing...
├── child_2-----------------------------> testing...
│   └── grandchild_21-------------------> testing...
└── child_3-----------------------------> testing...
    └── grandchild_31-------------------> testing...
Kevin
  • 74,910
  • 12
  • 133
  • 166