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
Python String encode() MethodThe encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions.
“latin-1” is another significant ASCII-compatible encoding, as it maps byte values directly to the first 256 Unicode code points.
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With