jeudi 4 juin 2015

Python encoding error? UnicodeDecodeError: 'ascii' codec can't decode byte ordinal not in range(128)

I have an AWS autoscale instance. On the AMI for that instance, I have a file myfile.py that contains the following string:

X5ZŒ

In my AWS Cloudformation, LaunchConfiguration, I have UserData that executes the following python instruction when the instance is spun up. It simply reads myfile.py and attempts to replace all occurrences of the regexp "X\dZ" with "XYZ":

myString = "XYZ".join(re.compile('X\d\Z').split(open("myfile.py", "r").read()))

That produces this error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4: ordinal not in range(128)

Okay. I understand that the character Œ is causing trouble because it is non-ASCII. But when I manually run the same statement from the python shell, it works fine without throwing any exception.

How can I force the script that is run by AWS LaunchConfig's UserData to have the same behavior as when I run it manually myself? What encoding should I set and how should I set it?




Aucun commentaire:

Enregistrer un commentaire