Sammy123
Sammy123

Reputation: 83

Program throws (Non-UTF-8 code starting with '\xff' in file) when running from command prompt

Below is the code:

def add(a,b):
    return a + b
while True:
    try:
        a=float(input('Please enter a number'))
        break
    except:
        print ('Invalid Number, please re-enter')
while True:
    try:
        b=float(input('Please enter a number'))
        break
    except:
        print ('Invalid Number, please re-enter')
print(add(a,b))

Upvotes: 6

Views: 26568

Answers (5)

Tuấn Nguyễn
Tuấn Nguyễn

Reputation: 11

Beside using notepad to encoding back to UTF-8, you can also do it in the vsc by click on the encoding displayed at the bottom right corner (in VS Code, it might say "UTF-16 LE) and choose save with encoding, select UTF-8 and it will be do the trick

This is the UI for select encoding format

You can also format UTF-8 when create file using cli echo with this syntax

   echo 'print("Hello World")' | Out-File "fileName.py" -Encoding utf8

enter image description here

Upvotes: 0

gurpartap
gurpartap

Reputation: 465

Event: Created a Python file via PowerShell; tried editing it in VS Code and got a similar error.
Issue: Powershell and VS Code encoding schema mismatch. See: Understanding file encoding in VS Code and PowerShell
Resolution: Recreated file using VS Code.

Upvotes: 9

Bhupinder
Bhupinder

Reputation: 31

The problem is that your .py files are in utf-16 encoding. While running a python script (.py) file it should be in utf-8 encoding by default.

In my case: I created a .py file using cmd/PowerShell prompt using

CMD prompt> echo #my First program > firstProgram.py

To fix the problem, open the file in notepad, select save as and change the encoding to utf-8 from utf-16.

Upvotes: 3

Sukrit Jangwang
Sukrit Jangwang

Reputation: 11

I was having the problem

I solved it by changing the encoding of the file to utf-8

  • Use windows 'notepad', click 'save as' then you'll notice the encoding section on the left of the save button. Select utf-8. then save the file.
  • In 'notepad++' you can change the encoding directly in the program by the top section written 'encoding'. Change it to 'utf-8'
  • Or in VSCode at the lowest bottom section on the right side, you'll see utf-8 or utf-16 or else. You can change encoding of the file there.

Like above comment said, I also created the file from PowerShell

  • wsl touch filename will create utf-8 (wsl is linux on windows)
  • echo "" > filename will create utf-16

Upvotes: 1

Dillon_Su
Dillon_Su

Reputation: 91

I think the issue may be how you are calling it form the command line. You should change directories to where your python interpreter is and then point it to the script

c:\users\test>cd c:\python2.7
c:\python2.7>python.exe "c:\users\test\desktop\test_script.py"

Just use the path to your python exe and then replace my desktop with the path to your script.

Upvotes: 3

Related Questions