I'm writing JSON data with special characters (å, ä, ö) to file and then reading it back in. Then I use this data in a subprocess command. When using the read data I cannot make special characters get translated back to å, ä and ö respectively.
When running the python script below, the list "command" is printed as:
['cmd.exe', '-Name=M\xc3\xb6tley', '-Bike=H\xc3\xa4rley', '-Chef=B\xc3\xb6rk']
But I want it to be printed like this:
['cmd.exe', '-Name=Mötley', '-Bike=Härley', '-Chef=Börk']
Python Script:
# -*- 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())