Skip to main content
 首页 » 编程设计

python之py2exe/py2app 和 docx 不能一起工作

2025年05月04日23jirigala

在此处的 Windows 7 上安装了 docx:

D:\Program Files (x86)\Python27\Lib\site-packages如下图:

在 OS X 上的/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/docx-0.0.2-py2.7.egg-info 中安装了 docx,如下所示:

以下是示例脚本(名为 docx_example.py),它在 python 解释器上运行得非常好:

#!/usr/bin/env python 
''' 
This file makes an docx (Office 2007) file from scratch, showing off most of python-docx's features. 
 
If you need to make documents from scratch, use this file as a basis for your work. 
 
Part of Python's docx module - http://github.com/mikemaccana/python-docx 
See LICENSE for licensing information. 
''' 
from docx import * 
 
if __name__ == '__main__':         
    # Default set of relationshipships - these are the minimum components of a document 
    relationships = relationshiplist() 
 
    # Make a new document tree - this is the main part of a Word document 
    document = newdocument() 
 
    # This xpath location is where most interesting content lives  
    docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0] 
 
    # Append two headings and a paragraph 
    docbody.append(heading('''Welcome to Python's docx module''',1)  )    
    docbody.append(heading('Make and edit docx in 200 lines of pure Python',2)) 
    docbody.append(paragraph('The module was created when I was looking for a Python support for MS Word .doc files on PyPI and Stackoverflow. Unfortunately, the only solutions I could find used:')) 
 
    # Add a numbered list 
    for point in ['''COM automation''','''.net or Java''','''Automating OpenOffice or MS Office''']: 
        docbody.append(paragraph(point,style='ListNumber')) 
    docbody.append(paragraph('''For those of us who prefer something simpler, I made docx.'''))  
 
    docbody.append(heading('Making documents',2)) 
    docbody.append(paragraph('''The docx module has the following features:''')) 
 
    # Add some bullets 
    for point in ['Paragraphs','Bullets','Numbered lists','Multiple levels of headings','Tables','Document Properties']: 
        docbody.append(paragraph(point,style='ListBullet')) 
 
    docbody.append(paragraph('Tables are just lists of lists, like this:')) 
    # Append a table 
    docbody.append(table([['A1','A2','A3'],['B1','B2','B3'],['C1','C2','C3']])) 
 
    docbody.append(heading('Editing documents',2)) 
    docbody.append(paragraph('Thanks to the awesomeness of the lxml module, we can:')) 
    for point in ['Search and replace','Extract plain text of document','Add and delete items anywhere within the document']: 
        docbody.append(paragraph(point,style='ListBullet')) 
 
    # Search and replace 
    print 'Searching for something in a paragraph ...', 
    if search(docbody, 'the awesomeness'): print 'found it!' 
    else: print 'nope.' 
 
    print 'Searching for something in a heading ...', 
    if search(docbody, '200 lines'): print 'found it!' 
    else: print 'nope.' 
 
    print 'Replacing ...', 
    docbody = replace(docbody,'the awesomeness','the goshdarned awesomeness')  
    print 'done.' 
 
    # Add a pagebreak 
    docbody.append(pagebreak(type='page', orient='portrait')) 
 
    docbody.append(heading('Ideas? Questions? Want to contribute?',2)) 
    docbody.append(paragraph('''Email <python.docx@librelist.com>''')) 
 
    # Create our properties, contenttypes, and other support files 
    coreprops = coreproperties(title='Python docx demo',subject='A practical example of making docx from Python',creator='Mike MacCana',keywords=['python','Office Open XML','Word']) 
    appprops = appproperties() 
    contenttypes = contenttypes() 
    websettings = websettings() 
    wordrelationships = wordrelationships(relationships) 
 
    # Save our document 
    savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships,'docx_example.docx') 

以下是用于创建独立程序(在 Mac OSX 中为 .app,在 Windows 7 中为 .exe)的设置脚本(名为 docx_setup.py):

import sys,os 
 
# Globals: START 
main_script='docx_example' 
dist_dir_main_path=os.path.abspath('./docx-bin') 
compression_level=2 
optimization_level=2 
bundle_parameter=1 
skip_archive_parameter=False 
emulation_parameter=False 
module_cross_reference_parameter=False 
ascii_parameter=False 
includes_list=['lxml.etree','lxml._elementpath','gzip'] 
# Globals: STOP 
 
# Global Functions: START 
def isDarwin(): 
    return sys.platform=='darwin' 
 
def isLinux(): 
    return sys.platform=='linux2' 
 
def isWindows(): 
    return os.name=='nt' 
# Global Functions: STOP 
 
if isDarwin(): 
    from setuptools import setup 
 
    # Setup distribution directory: START 
    dist_dir=os.path.abspath('%s/osx' %(dist_dir_main_path)) 
    if os.path.exists(dist_dir): 
        os.system('rm -rf %s' %(dist_dir)) 
    os.system('mkdir -p %s' %(dist_dir)) 
    # Setup distribution directory: STOP 
 
    APP = ['%s.py' %(main_script)] 
    OPTIONS={'argv_emulation': False, 
             'dist_dir': dist_dir, 
             'includes': includes_list 
            } 
    print 'Creating standalone now...' 
    setup(app=APP,options={'py2app': OPTIONS},setup_requires=['py2app']) 
    os.system('rm -rf build') 
    os.system('tar -C %s -czf %s/%s.tgz %s.app' %(dist_dir,dist_dir,main_script,main_script)) 
    os.system('rm -rf %s/%s.app' %(dist_dir,main_script))     
    print 'Re-distributable Standalone file(s) created at %s/%s.zip. Unzip and start using!!!' %(dist_dir,main_script)     
 
elif isWindows(): 
    from distutils.core import setup 
    import py2exe 
 
    # Setup distribution directory: START 
    dist_dir=os.path.abspath('%s/win' %(dist_dir_main_path)) 
    if os.path.exists(dist_dir): 
        os.system('rmdir /S /Q %s' %(dist_dir)) 
    os.system('mkdir %s' %(dist_dir)) 
    # Setup distribution directory: STOP 
 
    OPTIONS={'compressed': compression_level, 
             'optimize': optimization_level, 
             'bundle_files': bundle_parameter, 
             'dist_dir': dist_dir, 
             'xref': module_cross_reference_parameter, 
             'skip_archive': skip_archive_parameter, 
             'ascii': ascii_parameter, 
             'custom_boot_script': '', 
             'includes': includes_list 
            } 
    print 'Creating standalone now...' 
    setup(options = {'py2exe': OPTIONS},zipfile = None,windows=[{'script': '%s.py' %(main_script)}]) 
    print 'Re-distributable Standalone file(s) created in the following location: %s' %(dist_dir) 
    os.system('rmdir /S /Q build') 

真正的问题来了。

以下是在尝试使用 docx_example.app 后在 Mac OS X 控制台上发布的错误,该应用程序是使用命令 python docx_setup.py py2app 创建的:

docx_example: Searching for something in a paragraph ... found it! 
docx_example: Searching for something in a heading ... found it! 
docx_example: Replacing ... done. 
docx_example: Traceback (most recent call last): 
docx_example:   File "/Users/admin/docx-bin/osx/docx_example.app/Contents/Resources/__boot__.py", line 64, in <module> 
docx_example:     _run('docx_example.py') 
docx_example:   File "/Users/admin/docx-bin/osx/docx_example.app/Contents/Resources/__boot__.py", line 36, in _run 
docx_example:     execfile(path, globals(), globals()) 
docx_example:   File "/Users/admin/docx-bin/osx/docx_example.app/Contents/Resources/docx_example.py", line 75, in <module> 
docx_example:     savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships,'docx_example.docx') 
docx_example:   File "docx.pyc", line 849, in savedocx 
docx_example: AssertionError 
docx_example: docx_example Error 
docx_example Exited with code: 255 

以下是在尝试使用 docx_example.exe 后在 Windows 7 的 docx_example.exe.log 文件中发布的错误,该文件是使用命令 python docx_setup.py py2exe 创建的:

Traceback (most recent call last): 
  File "docx_example.py", line 75, in <module> 
  File "docx.pyo", line 854, in savedocx 
WindowsError: [Error 3] The system cannot find the path specified: 'D:\\docx_example\\docx_example.exe\\template' 

如您所见,OS X 和 Windows 7 在这里指的是类似的东西。请帮忙。

请您参考如下方法:

我找到了解决办法

在 api.py 中

来自

_thisdir = os.path.split(__file__)[0] 

到

_thisdir = 'C:\Python27\Lib\site-packages\docx' 

或者无论你的 docx 文件是什么