1

i have a script which should take one parameter from command line. I have a problem to parse a special characters like currency symbols ($, €, £). It is possible to correctly parse these arguments in python. Code looks like:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", type=str, required=True)
    args = parser.parse_args()
    print args.input

if __name__ == '__main__':
    main()

When i run it from cmd on Windows

./myCode --input $
$

it print $ fine. But it is not working for € and £. How can I correctly encode these characters from command line?

./myCode --input £
L

./myCode --input €
UnicodeDecodeError
Daniel
  • 51
  • 8
  • 1
    i have tried it but type=lambda s: unicode(s, 'utf8') not working, output is still same. – Daniel Mar 05 '17 at 11:31
  • Look at the strings in the `sys.argv`. The `type` parameter should be a function, something that converts the `sys.argv` value to what you want. – hpaulj Mar 05 '17 at 11:49
  • try this, print unicode(str(args.input), encoding="utf-8") – Dan Temkin Mar 05 '17 at 11:50
  • Python 2 uses the Windows ANSI encoded command line. Install [`win_unicode_console`](https://pypi.python.org/pypi/win_unicode_console) and enable it with `win_unicode_console.enable(use_unicode_argv=True)`. But then Python 2 argparse will fail to handle the `unicode` strings, so next you have to encode `sys.argv` using UTF-8, e.g. `sys.argv = [x.encode('utf-8') for x in sys.argv]`. Then import argparse, and it should work. Or just install Python 3.6 and have all of this working without having to hack around the legacy cruft in Python 2. – Eryk Sun Mar 05 '17 at 17:11
  • Second the suggestion to use Python 3.6. – Roland Smith Mar 05 '17 at 17:44

0 Answers0