我正在将带有特殊字符(å、ä、ö)的 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())