Lecture de caractères Unicode à partir des arguments de ligne de commande en Python 2.x sous Windows

StackOverflow https://stackoverflow.com/questions/846850

Question

Je veux que mon script Python pour pouvoir lire les arguments de ligne de commande Unicode dans Windows. Mais il semble que sys.argv est une chaîne codée dans un codage local, plutôt que Unicode. Comment puis-je lire la ligne de commande en pleine Unicode?

Exemple de code: argv.py

import sys

first_arg = sys.argv[1]
print first_arg
print type(first_arg)
print first_arg.encode("hex")
print open(first_arg)

Sur mon PC mis en place pour la page de code japonais, je reçois:

C:\temp>argv.py "PC・ソフト申請書08.09.24.doc"
PC・ソフト申請書08.09.24.doc
<type 'str'>
50438145835c83748367905c90bf8f9130382e30392e32342e646f63
<open file 'PC・ソフト申請書08.09.24.doc', mode 'r' at 0x00917D90>

C'est codé Shift-JIS je crois, et il « fonctionne » pour ce nom de fichier. Mais il casse des noms de fichiers avec des caractères qui ne sont pas dans le set-finale appel « ouvert » Shift-JIS échoue:

C:\temp>argv.py Jörgen.txt
Jorgen.txt
<type 'str'>
4a6f7267656e2e747874
Traceback (most recent call last):
  File "C:\temp\argv.py", line 7,
in <module>
    print open(first_arg)
IOError: [Errno 2] No such file or directory: 'Jorgen.txt'

Notez-je parle Python 2.x, pas Python 3.0. J'ai trouvé que Python 3.0 donne comme Unicode approprié sys.argv. Mais il est un peu tôt pour la transition vers Python 3.0 (en raison du manque de soutien de la bibliothèque 3ème partie).

Mise à jour:

Quelques réponses ont dit que je dois décoder selon quel que soit le <=> est codé. Le problème qui est que ce n'est pas plein Unicode, de sorte que certains personnages ne sont pas représentables.

Voici le cas d'utilisation qui me donne le chagrin: je permis de glisser-déposer des fichiers sur les fichiers py dans l'Explorateur Windows . J'ai des noms de fichiers avec toutes sortes de personnages, dont certains pas dans la page de code par défaut du système. Mon script Python ne reçoit pas les bons noms de fichiers Unicode qui lui sont transmises par l'intermédiaire sys.argv dans tous les cas, lorsque les personnages ne sont pas représentables dans le codage de la page courante de code.

Il y a certainement une API Windows pour lire la ligne de commande avec Unicode complète (et Python 3.0 ne est-ce). Je suppose que l'interpréteur Python 2.x ne l'utilise pas.

Était-ce utile?

La solution

Here is a solution that is just what I'm looking for, making a call to the Windows GetCommandLineArgvW function:
Get sys.argv with Unicode characters under Windows (from ActiveState)

But I've made several changes, to simplify its usage and better handle certain uses. Here is what I use:

win32_unicode_argv.py

"""
win32_unicode_argv.py

Importing this will replace sys.argv with a full Unicode form.
Windows only.

From this site, with adaptations:
      http://code.activestate.com/recipes/572200/

Usage: simply import this module into a script. sys.argv is changed to
be a list of Unicode strings.
"""


import sys

def win32_unicode_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    if argc.value > 0:
        # Remove Python executable and commands if present
        start = argc.value - len(sys.argv)
        return [argv[i] for i in
                xrange(start, argc.value)]

sys.argv = win32_unicode_argv()

Now, the way I use it is simply to do:

import sys
import win32_unicode_argv

and from then on, sys.argv is a list of Unicode strings. The Python optparse module seems happy to parse it, which is great.

Autres conseils

Dealing with encodings is very confusing.

I believe if your inputing data via the commandline it will encode the data as whatever your system encoding is and is not unicode. (Even copy/paste should do this)

So it should be correct to decode into unicode using the system encoding:

import sys

first_arg = sys.argv[1]
print first_arg
print type(first_arg)

first_arg_unicode = first_arg.decode(sys.getfilesystemencoding())
print first_arg_unicode
print type(first_arg_unicode)

f = codecs.open(first_arg_unicode, 'r', 'utf-8')
unicode_text = f.read()
print type(unicode_text)
print unicode_text.encode(sys.getfilesystemencoding())

running the following Will output: Prompt> python myargv.py "PC・ソフト申請書08.09.24.txt"

PC・ソフト申請書08.09.24.txt
<type 'str'>
<type 'unicode'>
PC・ソフト申請書08.09.24.txt
<type 'unicode'>
?日本語

Where the "PC・ソフト申請書08.09.24.txt" contained the text, "日本語". (I encoded the file as utf8 using windows notepad, I'm a little stumped as to why there's a '?' in the begining when printing. Something to do with how notepad saves utf8?)

The strings 'decode' method or the unicode() builtin can be used to convert an encoding into unicode.

unicode_str = utf8_str.decode('utf8')
unicode_str = unicode(utf8_str, 'utf8')

Also, if your dealing with encoded files you may want to use the codecs.open() function in place of the built-in open(). It allows you to define the encoding of the file, and will then use the given encoding to transparently decode the content to unicode.

So when you call content = codecs.open("myfile.txt", "r", "utf8").read() content will be in unicode.

codecs.open: http://docs.python.org/library/codecs.html?#codecs.open

If I'm miss-understanding something please let me know.

If you haven't already I recommend reading Joel's article on unicode and encoding: http://www.joelonsoftware.com/articles/Unicode.html

Try this:

import sys
print repr(sys.argv[1].decode('UTF-8'))

Maybe you have to substitute CP437 or CP1252 for UTF-8. You should be able to infer the proper encoding name from the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\OEMCP

The command line might be in Windows encoding. Try decoding the arguments into unicode objects:

args = [unicode(x, "iso-8859-9") for x in sys.argv]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top