Differences between revisions 1 and 3 (spanning 2 versions)
Revision 1 as of 2005-01-13 22:28:12
Size: 846
Editor: av9361
Comment:
Revision 3 as of 2005-09-11 08:23:47
Size: 988
Editor: FredDrake
Comment: copyedit; add link to locale module docs
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
If you try to redirect printing of non-ascii unicode string into a file Python doesn't know how to encode non-ascii characters because there are many text encoding in use across the world. You need to wrap standard output with encoder that will convert unicode characters into encoding of you choice. For example to convert characters into utf-8 encoding use If you try to redirect printing of non-ASCII unicode strings into a file, Python doesn't know how to encode non-ascii characters because there are many text encodings in use across the world. You need to wrap standard output with an encoder that will convert unicode characters into encoding of your choice. For example, to convert characters into utf-8 encoding use:
Line 7: Line 7:
Of course this code is not portable since most users in the world don't use utf-8 encoding for files. locale module provides function getpreferredencoding that will try to guess what is the preffered encoding for text files. There are also other ways to ask user for encoding of text files: command line options of your script, parameter stored in a configuration file, GUI dialog and so on... Of course, this code is not portable since most users in the world don't use UTF-8 encoding for files. The `locale` module provides the function `getpreferredencoding()` that will try to guess what is the preferred encoding for text files. There are also other ways to ask user for encoding of text files: command line options of your script, parameters stored in a configuration file, and GUI dialogs are common examples.

=== References ===

 * [http://docs
.python.org/lib/module-locale.html locale module documentation]

If you try to redirect printing of non-ASCII unicode strings into a file, Python doesn't know how to encode non-ascii characters because there are many text encodings in use across the world. You need to wrap standard output with an encoder that will convert unicode characters into encoding of your choice. For example, to convert characters into utf-8 encoding use:

   1 import codecs
   2 sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__)

Of course, this code is not portable since most users in the world don't use UTF-8 encoding for files. The locale module provides the function getpreferredencoding() that will try to guess what is the preferred encoding for text files. There are also other ways to ask user for encoding of text files: command line options of your script, parameters stored in a configuration file, and GUI dialogs are common examples.

References

ShellRedirectionFails (last edited 2008-11-15 14:01:25 by localhost)

Unable to edit the page? See the FrontPage for instructions.