Search code examples
pythonnumbersruntime-errorlinetraceback

No line number shown for run-time error from Python module


Most Python errors produce traceback showing the line number of the offending statement. But for some reason some run-time errors do not.

For instance, running "python -m mymodule.py" on a module containing just the two lines:

args = {}
if len(args > 2): print("this is a run-time error. Should be: len(args) > 2")

fails with:

c:\python34\python.exe: Error while finding spec for 'mymodule.py' (<class 'TypeError'>: unorderable types: dict() > int())

This sample of code was from a much larger module which failed and, having no line number made it hard to find the coding error.


Solution

  • When you use -m, python searches sys.path for the module, and it's not finding the file you specified. This is because the path doesn't (and for reasons of stability and security normally shouldn't) include the current working directory.

    Since the error is produced at the command line rather than inside your file, there is no line number for the error.

    Finally, to fix the problem, type

    python -m ./mymodule
    

    This fixes two problems from your command line:

    1. The .py extension is omitted when doing a module import.

    2. You need to explicitly add the path in order to import this module (or move it into a directory in sys.path).