Question

I've a Python file titled my_python_file.py that makes, among other things, a .doc file using the python-docx module. The .doc is created perfectly and gives no problem. The problem comes when I build a .exe of my script and I try to make the .doc. An AssertionError problem appears.

This is my exe maker code (exe_maker.py):

from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 3, 'compressed': True, 'includes': ['lxml.etree', 'lxml._elementpath', 'gzip', 'docx']}},
    windows = [{'script': "my_python_file.py"}],
    zipfile = None,
)

It seems that moving the python script to a different location produces the error.

  File "docx.pyc", line 1063, in savedocx
AssertionError

This is the savedocx line:

document = newdocument()
[...]
coreprops = coreproperties(title=title, subject=subject, creator=creator, keywords=keywords)
approps = appproperties()
contenttypes2 = contenttypes()
websettings2 = websettings()
wordrelationships2 = wordrelationships(relationships)
path_save = "C:\output"
savedocx(document, coreprops, approps, contenttypes2, websettings2, wordrelationships2, path_save)

The savedox is well writen as it works when it's not an .exe file.

How can I make the docx module work correctly? Do I've to add any other path/variable more when I make the exe?

Thanks in advance

Was it helpful?

Solution

I solved the problem by edditing the api.py file of docx egg folder which is located in the Python folder of the system.

Changing this:

_thisdir = os.path.split(__file__)[0]
_default_docx_path = os.path.join(_thisdir, 'templates', 'default.docx')

To this:

thisdir = os.getcwd()
_default_docx_path = os.path.join(thisdir, 'templates', 'default.docx')

The first one was taking the actual running program and adding it to the path to locate the templates folder.
C:\myfiles\myprogram.exe\templates\default.docx

The solution takes only the path, not the running program.
C:\myfiles\templates\default.docx

OTHER TIPS

Instead of changing some library file, I find it easier and cleaner to tell python-docx explicitly where to look for the template, i.e.:

document = Document('whatever/path/you/choose/to/some.docx')

This effectively solves the py2exe and docx path problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top