2017-07-19 7 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の結果は、WindowsおよびLinux上の'utf-8'でもあったけど。

私が期待される出力に達する可能性が最も近いが、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に設定しても機能しませんでした。それでも同じ出力が表示されます。 –

関連する問題