user4404699 user4404699 - 3 months ago 22
Python Question

Cannot run python script under powershell in spite of adding env Path as required

I am a user of python under mac and need to work now on a windows system.
I have installed Python35 for windows in Powershell, the command

py --version
and
python --version
provides me "Python 3.5.2".

I want to run a python script in Powershell and have tried :
py file.py
python file.py
py .\file.py
python .\file.py

and have the following :

python : File ".\file.py", line 1
Au caractère Ligne:1 : 1
+ python .\file.py
+ ~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: ( File ".\file.py", line 1:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

SyntaxError: Non-UTF-8 code starting with '\xff' in file .\file.py on line 1, but no encoding declared; see
http://python.org/dev/peps/pep-0263/ for details


As for
.\file.py
it opens me a black window that closes within 1 second.

Interestingly, when doing
python
or
py
it outputs the python idle but powershell is blocked and I cannot use it either in powershell.

Now, I already looked at

cannot run python script file using windows prompt

Cannot run python script

Run python script inside powershell script

As well as I tried to add the Python Path in Powershell and manully in the "Advance system" interface of windows.

By the way my
file.py
contains a simple
print("hello")


What am I doing wrong?

Answer

The problem is explained in the error message:

SyntaxError: Non-UTF-8 code starting with '\xff' in file .\file.py on line 1, but no encoding declared;

It means that Python reads the source file and gets confused. On the other hand, it has a byte order mark header, but on the other hand there isn't enough information about what kind of Unicode the file is about.

It's better be safe than sorry, so Python requires you to tell what to do instead of trying to guess what's the real encoding. In unicode, you see, there are caveats. For example, ½ is actually a number that has value of 0.5.

As for how to solve this, either save the file as non-unicode (ANSI) or start the source file with, say, header:

# -*- coding: utf-8 -*-