Search code examples
pythonpython-2.7line-profiler

How do I fix an unusual SyntaxError in the python executable itself when running line_profiler?


Here's a strange one.

First of all: This is NOT a problem with the encoding of a python script file that I have written myself or am importing (see e.g. Working with UTF-8 encoding in Python source and the many duplicates thereof).

I am running the excellent line_profiler over some python2.7 code in a virtual env. The SyntaxError is pointing to the python executable itself! So obviously(?) I can't add an encoding line at the top.

Is this perhaps an issue with line_profiler? Otherwise how on earth to proceed?

Here is the traceback:

(myenv)$ kernprof -l python main.py
Wrote profile results to python.lprof
Traceback (most recent call last):
  File "[snip]/myenv/bin/kernprof", line 8, in <module>
    sys.exit(main())
  File "[snip]/myenv/lib/python2.7/site-packages/kernprof.py", line 226, in main
    execfile(script_file, ns, ns)
  File "[snip]/myenv/bin/python", line 1
SyntaxError: Non-ASCII character '\xcf' in file [snip]/myenv/bin/python on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Solution

  • The answer is to make main.py executable, i.e. add the shebang to the top:

    #!/usr/bin/env python
    

    And chmod +x main.py - then:

    kernprof -l ./main.py
    

    Who knew!