2017-07-19 102 views
1

代碼的輸出在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 

回答

0

我能夠通過使用codecs得到預期的輸出。這 answer幫助了我。 使用編解碼器工作。

tree_structure = codecs.escape_decode(bytes(tree_structure, "utf-8"))[0].decode("utf-8") 
0

這是最有可能與您的Windows終端,而不是一個問題與您的代碼。

嘗試在控制檯中設置chcp 65001,該控制檯將代碼頁更改爲UTF-8。 print("├")之後適合我。

https://technet.microsoft.com/en-us/library/bb490874.aspx

+0

將代碼頁設置爲UTF-8不起作用。它仍然顯示相同的輸出。 –

相關問題