Search code examples
pythonpy2exeply

Using py2exe packing python program with ply got strange error?


I downloaded the PLY, and ran a simple test in ply3.8/test/calclex.py

# -----------------------------------------------------------------------------
# calclex.py
# -----------------------------------------------------------------------------
import sys

if ".." not in sys.path: sys.path.insert(0,"..")
import ply.lex as lex

tokens = (
    'NAME','NUMBER',
    'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
    'LPAREN','RPAREN',
    )

# Tokens

t_PLUS    = r'\+'
t_MINUS   = r'-'
t_TIMES   = r'\*'
t_DIVIDE  = r'/'
t_EQUALS  = r'='
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_NUMBER(t):
    r'\d+'
    try:
        t.value = int(t.value)
    except ValueError:
        print("Integer value too large %s" % t.value)
        t.value = 0
    return t

t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
lexer = lex.lex()

it works well. But when I use py2exe packing it to executable file. When run it, I get an error like:

Traceback (most recent call last):
  File "calclex.py", line 46, in <module>
    lexer = lex.lex()
  File "ply\lex.pyc", line 906, in lex
  File "ply\lex.pyc", line 580, in validate_all
  File "ply\lex.pyc", line 822, in validate_rules
  File "ply\lex.pyc", line 833, in validate_module
  File "inspect.pyc", line 690, in getsourcelines
  File "inspect.pyc", line 526, in findsource
  File "inspect.pyc", line 403, in getfile
TypeError: <module '__main__' (built-in)> is a built-in module

Has anyone tried to pack the ply to executable file?
And my setup.py is as follows:

from distutils.core import setup
import py2exe
setup(console=["calclex.py"])

Solution

  • Ply insists that its grammars be defined in real files, not virtualized filesystems. So it won't work with py2exe or pyinstaller or other such programmers which attempt to pack python source files into single archives. (See also Pyinstaller and Ply IOError: source code not available.)

    I don't know of a simple workaround. Perhaps it should be reported as a feature request to the Ply maintainers.