This question has been flagged

I Know is not exactly related to Odoo but Python in general, but I'm getting serious issues creating a simple text file on Windows.

Back story: I have a customer who asked for a custom module to integrate Odoo with his fiscal software here in Brazil. The task was pretty easy, grab infos from POS Order of products and services (product.template inherited with some field to match the fiscal information) and create a .txt on a shared folder to pull automatically the bill inside the other proprietary software.
All working fine on Linux, but fact is the client want all installed under Windows. 
My custom module works fine but I have issues with the encoding, since it can't decode chars like ã or é or ç.  

pgto = '\n'.join(str(e) for in pgto).replace('.', ',').upper()

f = open(str("/media/pedidos/" self.pos_reference + ".txt"), "w+")
f.write(pgto.encode('cp1252'))

will create the following txt under Linux:

PEDIDO|CONSUMIDOR NÃO IDENTIFICADO||CAIXA||
ITEM|83002|GUARANÁ 350ML|4,5|1|UN|22021000|17,3|20,0|0,0|IBPT|5405|500|0|0300800|
PGTO|01|4,5|

but the same txt created under Windows results in:

PEDIDO|CONSUMIDOR NÃcO IDENTIFICADO||CAIXA||
ITEM|83002|GUARANá 350ML|4,5|1|UN|22021000|17,3|20,0|0,0|IBPT|5405|500|0|0300800|
PGTO|01|4,5|

Since I've worked with Linux to Windows conversion in the past was quite easy find the correct encoding for Windows (cp1252), doesn't seems as simple as write from Windows to Windows...

I tried with various decode (UTF-8, Latin-1 and so on), but until now with no appreciable results.

Please note I'm dealing with strings inside a var, is not easy add a u' on any field pulled from the DB before creating the text file.
Any clue?

Avatar
Discard
Author Best Answer

Solved!

There are two solution for this kind of encoding issues under Windows but both may lead to some risks.

1. change the header of the model.py:

From

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

To

# -*- coding: cp1252 -*-

This coding will definitely solve the issue when writing on txt, but if you are updating  the DB on the same function at the same time, it could lead to some encoding issue inside the database.

2. Change sys property "on-the-fly":

Is the best solution for me. you can literally hack the sys default enconding and back to UTF-8 without messing too much. Just put in your code this:

import sys
reload (sys)
sys.setdefaultencoding('cp1252')

Problem solved, didn't find (for now) any issue using this method.
Anyway, my first module for Windows was finally deployed.

Avatar
Discard