代碼的輸出在Linux和Windows上有所不同。我對編碼不太熟悉,這就是這個問題似乎涉及的問題。Python3:sys.stdout在linux和windows上給出了不同的結果
這裏是我的代碼:
import sys
from treelib import Tree
from io import StringIO
# creating and populating tree
tree = Tree()
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Mark", "mark", parent="jane")
# var to store standard output
output = StringIO()
sys.stdout = output
tree.show()
# restoring standard output to console
sys.stdout = sys.__stdout__
tree_structure = output.getvalue()
print(tree_structure)
我得到的Linux,但在Windows結果已字符編碼爲\ XNN預期的輸出。
Linux的輸出:
Harry
├── Bill
└── Jane
├── Diane
│ └── Mary
└── Mark
的Windows輸出:
b'Harry\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Bill\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Jane\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 Diane\n \xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Mary\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 Mark\n'
雖然的sys.stdout.encoding
結果是既'utf-8'
在Windows和Linux。
我能達到預期的輸出最接近的是通過print語句之前添加以下:
#removing b'' from string
tree_structure = tree_structure[2:-2]
# converting to bytes
tree_structure = bytes(tree_structure,'utf-8')
tree_structure = tree_structure.decode('unicode_escape')
print(tree_structure)
輸出之後:
Harry
âââ Bill
âââ Jane
âââ Diane
â âââ Mary
âââ Mark
將代碼頁設置爲UTF-8不起作用。它仍然顯示相同的輸出。 –