py2exe/py2app 和 docx 不能一起工作

2023-12-30

在 Windows 7 上安装 docx:

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

Installed docx on OS X at /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/docx-0.0.2-py2.7.egg-info as shown below: enter image description here

以下是示例脚本(名为 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 <[email protected] /cdn-cgi/l/email-protection>'''))

    # 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')

现在真正的问题来了。

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

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

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

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 中

From

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

To

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

py2exe/py2app 和 docx 不能一起工作 的相关文章

随机推荐

  • 将 Java 8 与 LibGDX 结合使用

    我正在使用 LibGDX 用 Ja va 编写一个游戏 仅desktop作为目标平台 我刚刚创建了一个新的 LibGDX 项目 并向其中导入了一些现有代码 但现在出现了一些错误 具体来说 使用diamond operator 例如这行代码
  • 设置 pandas 图的图例位置

    我知道如何设置 matplotlib 图的图例位置plt legend loc lower left 但是 我正在用 pandas 方法进行绘图df plot 并需要将图例位置设置为 左下 有谁知道该怎么做 编辑 我实际上正在寻找一种通过
  • 我们如何在 Ionic App 中实现 SignalR?

    我制作了一个应用程序 可以向已注册该应用程序 Ionic Angular 的用户发送消息 它从数据库 SQL Server C API 获取所有消息并在消息框中打印出来 这很好 但是当我们向正在交谈的人发送消息时 该人在不刷新页面的情况下不
  • 在 Rails 中,如何在 i18n 语言环境文件中指定默认 flash 消息

    我知道 i18n 语言环境文件中有一些预设结构 以便 Rails 自动提取值 例如 如果您想为新记录设置默认提交按钮文本 config locales en yml en helpers submit create Create model
  • MySQL表可以存储的最大记录数是多少?

    MySQL MyISAM 表可以存储多少条记录 InnoDB可以有多少个 您无法按记录数进行计数 因为您的表可能包含只有几个 int 字段的非常短的记录 或者您的记录可能非常长且包含数百个字段 因此必须以表的文件大小来衡量 对于 MYSQL
  • 由不同操作成功触发的 Github Action

    我试图在成功运行不同的操作后触发 Github 操作来运行 这两个工作流程是 单元测试操作 首先运行 并且应该触发下面的 后续测试 操作 name unit tests on push branches jobs build runs on
  • 我正在用 microsoft Visual Studio 做我的 C++ 作业,我注意到一些不寻常的事情 [重复]

    这个问题在这里已经有答案了 当我尝试获取动态数组中插槽的数据时 出现异常 但是如果我使用不同的编译器 例如在线编译器 运行相同的代码 https www onlinegdb com online c compiler https www o
  • 如何绘制 z = f(x, y) 的平滑二维彩色图

    我正在尝试绘制二维现场数据使用 matplotlib 所以基本上我想要类似的东西 在我的实际情况中 我将数据存储在硬盘驱动器上的文件中 然而 为了简单起见 请考虑函数 z f x y 我想要一个平滑的二维图 其中 z 使用颜色可视化 我使用
  • 如何使用 JQuery 和跨站点脚本编写 ajax?

    我遇到一个问题 我必须从这里获取 json http templodasdeusas com br game srv game php srv home http templodasdeusas com br game srv game p
  • 使用属性 XmlSerialize 自定义集合

    我有一个简单的类 它继承自 Collection 并添加了几个属性 我需要将此类序列化为 XML 但 XMLSerializer 会忽略我的附加属性 我认为这是因为 XMLSerializer 对 ICollection 和 IEnumer
  • 在 C++ 中打印完整的回溯

    我想以与 gdb 中类似的格式从 Linux 中的 C 程序转储回溯 我尝试使用 backtrace 和 backtrace symbols 函数来实现此目的 这些返回的函数名称和偏移量 我可以使用 cxa demangle 函数来获取可读
  • 如何通过按按钮关闭 Tkinter 窗口?

    编写一个带有标签的 GUI 应用程序 Good bye 当 的时候Button单击后 窗口关闭 到目前为止 这是我的代码 但它不起作用 谁能帮我解决我的代码吗 from Tkinter import window Tk def close
  • 通用铸造

    我怀疑答案是否定的 但是是否可以在 C NET v2 0 中执行类似的操作 class Converter
  • 在参数中设置symfony缓存目录

    我正在为 Symfony 应用程序构建 docker 环境 我每个应用程序都有一个容器 其中附加了一个仅用于链接到应用程序服务器的 Web 根数据的容器 作为基础设施安全强化的一部分 这些数据容器被设置为只读 以防止任何远程代码攻击 每个应
  • 如何使用 Java Scanner 测试空行?

    我期待使用扫描仪进行输入 直到没有任何内容 即当用户输入空行时 我该如何实现这一目标 I tried while scanner hasNext process input 但这会让我陷入循环 这是一个方法 Scanner keyboard
  • 如何覆盖 Angular Material 2 日期选择器的模板

    我需要修改 Angular 2 材质日期选择器的模板 它的模板在 angular material esm5 datepicker es5 js 中定义的几个内部组件中声明 我可以直接在节点包中修改模板 但是更新时它会被覆盖 我可以看到这种
  • Heroku 进程以状态 0 退出,但其 dyno 仍然“崩溃”

    我有一个用 ruby 编写的报废脚本 在工作台内的 Heroku 上运行 即使脚本运行顺利并以状态 0 退出 heroku 仍然告诉我测功机崩溃了 2016 12 13T00 59 10 695566 00 00 heroku spider
  • Python 可以用于客户端 Web 开发吗? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • ElapsedTicks、ElapsedMilliseconds、Elapsed.Milliseconds 和 Elapsed.TotalMilliseconds 之间的区别? (C#)

    我对这4个完全感到困惑 ElapsedMilliseconds long ElapsedTicks long Elapsed TotalMilliseconds double 和 Elapsed Milliseconds int 之间有什么
  • py2exe/py2app 和 docx 不能一起工作

    在 Windows 7 上安装 docx D Program Files x86 Python27 Lib site packages 如下所示 Installed docx on OS X at Library Frameworks Py