Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

python - Changing the preferred encoding for Windows7 command prompt

Using Python3.3

Running a python script to do some CAD file conversion, but getting below error

Conversion Failed
Traceback (most recent call last):
File "Start.py", line 141, in convertLib
lib.writeLibrary(modFile,symFile)
File "C:Python33Eagle2Kicad/LibraryLibrary.py", line 67, in writeLibrary
self.writeSymFile(symFile)
File "C:Python33Eagle2Kicad/LibraryLibrary.py", line 88, in writeSymFile
devicepart.write(symFile)
File "C:Python33Eagle2Kicad/CommonSymbol.py", line 51, in write
symbol.write(symFile)
File "C:Python33Eagle2Kicad/CommonSymbol.py", line 114, in write
symFile.write(pin.symRep())
File "C:Python33Libencodingscp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character 'x96' in position 4:     character maps to <undefined>

It seems the preferred encoding in my Windows7 command prompt is NOT cp1252 (typing chcp shows "Active code page 437"). How can I change it to cp1252?

Can anyone please suggest?

EDIT:

As the default preferred encoding of the python command line is cp1252, I tried running the script from python command line instead of the windows command prompt. But I am still getting the same error as above. Can anyone please suggest?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When writing to files, the console encoding is not taken into account; only the locale is. From the open() function documenation:

In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.

On your system, evidently that call returns 'cp1252'. The remedy is to always name the encoding for files explicitly; pass in an encoding argument to set the desired encoding for files:

with open(filename, 'w', encoding='utf8') as symFile:

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...