doejs doejs - 3 months ago 9
Python Question

Have Code Change Terminal Settings Upon Load

I have a program that requires me to enter

chcp 65001
and
set PYTHONIOENCODING=utf-8
before I run the code, or it cannot process characters properly. Is there a way to have the code automatically do this upon opening? Its a pain, and easy to forget, to do this every time.

Answer

Actually, you should be able to do this within Python, but supposing that its runtime has this requirement, you can do these settings in a batch file before calling python with your script. For example, suppose this script is called pyutf8.bat :

@echo off
setlocal
chcp 65001
set PYTHONIOENCODING=utf-8
python %1 %2 %3 %4 %5 %6 %7 %8 %9

then you could run your script using this:

pyutf8 myscript.py

The %1, etc., are the positional parameters of the script. You can check if no parameters were given, using that to supply a default parameter. Something like this:

@echo off
setlocal
chcp 65001
set PYTHONIOENCODING=utf-8
if "%1"=="" goto default
python %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof
:default
python myscript.py

Further reading:

Comments