0

特殊文字 (å、ä、ö) を含む JSON データをファイルに書き込み、それを読み込んでいます。次に、このデータをサブプロセス コマンドで使用します。読み取ったデータを使用する場合、特殊文字をそれぞれ å、ä、ö に変換することはできません。

以下の python スクリプトを実行すると、リスト「コマンド」は次のように出力されます。

['cmd.exe', '-Name=M\xc3\xb6tley', '-Bike=H\xc3\xa4rley', '-Chef=B\xc3\xb6rk']

しかし、私はそれを次のように印刷したい:

['cmd.exe', '-Name=Mötley', '-Bike=Härley', '-Chef=Börk']

Python スクリプト:

# -*- coding: utf-8 -*-

import os, json, codecs, subprocess, sys


def loadJson(filename):
    with open(filename, 'r') as input:
        data = json.load(input)
    print 'Read json from: ' + filename
    return data

def writeJson(filename, data):
    with open(filename, 'w') as output:
        json.dump(data, output, sort_keys=True, indent=4, separators=(',', ': '))
    print 'Wrote json to: ' + filename



# Write JSON file
filename = os.path.join( os.path.dirname(__file__) , 'test.json' )
data = { "Name" : "Mötley", "Bike" : "Härley", "Chef" : "Börk" }
writeJson(filename, data)


# Load JSON data
loadedData = loadJson(filename)


# Build command
command = [ 'cmd.exe' ]

# Append arguments to command
arguments = []
arguments.append('-Name=' + loadedData['Name'] )
arguments.append('-Bike=' + loadedData['Bike'] )
arguments.append('-Chef=' + loadedData['Chef'] )
for arg in arguments:
    command.append(arg.encode('utf-8'))

# Print command (my problem; these do not contain the special characters)
print command

# Execute command
p = subprocess.Popen( command , stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# Read stdout and print each new line
sys.stdout.flush()
for line in iter(p.stdout.readline, b''):
    sys.stdout.flush()
    print(">>> " + line.rstrip())
4

1 に答える 1