【发布时间】:2013-10-02 13:27:45
【问题描述】:
我正在将带有特殊字符(å、ä、ö)的 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())
【问题讨论】:
-
打印列表中的字符串而不是列表,特殊字符会神奇地重新出现
-
M\xc3\xb6tley是Mötley,用utf8编码,就像你写的那样。你的代码很好。 -
@hop - 这样打印列表只是为了说明这些值不包含 åöä 字符。它在 subprocess.Popen 中,我遇到了真正的问题,因为参数不包含 åöä 字符。
-
Unicode in python 的可能重复项
-
@fredrik:a) 你错了。 b)您的问题可能是Windows。 c) 你确定 cmd.exe 可以处理 utf-8 吗?