9

PEP0263 specifies a syntax to declare the encoding of a Python source file within the source file itself.

Is it possible to specify the encoding from the command line?

Or is there a reason why this might be undesirable?

I'm thinking of something like:

$ python --encoding utf-8 myscript.py 

or even:

$ PYTHONSOURCEENCODING=utf-8 python myscript.py 
2
  • And then it should override the encoding specified in the source file, if specified?
    – aldeb
    CommentedMay 18, 2015 at 8:56
  • You could go both ways on this. You might want to override an encoding incorrectly specified in the source file. On the other hand you might want to say "use the encoding specified on the command line unless an encoding is specified in the source file."CommentedMay 18, 2015 at 9:08

2 Answers 2

3

This is a hack, and isn't what you're looking for, and it doesn't work on systems that don't have sed, but you can prepend the coding line to any python script by using sed '1s/^/# -*- coding: utf-8 -*-\n/' script.py | python.

To make this more generalized, you can define a function in your .bashrc or profile.

As an aside, I think the reason that this wasn't implemented in the first place is that encoding is and should be considered a property of each file itself, not the call that spawns the thread. The conceptual spaces in which file encoding and process spawning exist are pretty different, at least to my thinking.

    1

    Although there could be special use cases where this feature could help, I think it could be confusing.

    When you execute a Python script, there can be 2 diffent encodings :

    • the source script encoding, which can be defined in the script itself via PEP0263
    • the environment encoding that can be defined through environment variables

    The former is static in the script and its only use is to allow programmer to use non ASCII characters in litteral strings

    The latter is what should be used for IO. It may change on different runs of the script.

    If you want to pass the script encoding on command line (or through environment variables) you add confusion with the local runtime system encoding.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.