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

Viewed 9994

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))
4 Answers

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.

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.

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
Related