2012-04-18 97 views
1

的docx安裝在Windows 7上的位置:py2exe/py2app和DOCX不共同努力

d:\程序文件(x86)\ Python27 \ LIB \如下圖所示站點包:

enter image description here

在OS X /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/docx-0.0.2-py2.7.egg-info上安裝了docx,如下所示: enter image description here

以下是示例腳本(命名爲docx_example.py),wh ICH運行在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]>''')) 

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

以下是安裝腳本(命名爲docx_setup.py)(在Mac OSX。應用程序和Windows 7中的.exe)創建獨立:

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: 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錯誤:

以下是試圖使用docx_example.app後的Mac OS X控制檯上張貼的錯誤,使用命令python docx_setup.py py2app創建在Windows 7 .log文件試圖使用docx_example.exe後,使用命令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指的是類似的東西在這裏。請幫忙。

+0

不是一個解決方案,但你有沒有嘗試過[cx_Freeze] (http://cx-freeze.sourceforge.net/)呢?我已經取得了很多成功(並且支持Python 3,支持Windows,Linux和OS X)。 – 2012-04-18 17:18:53

+0

如果您打開py2exe生成的庫文件是目前的docx模塊,以及它的模板目錄?您應該可以使用任何zip /歸檔程序打開該文件。 – 2012-04-18 17:25:59

回答

0

發生了什麼(至少對於py2exe)與this question類似。

data_files的文檔是here

什麼你基本上做的是改變

setup(options = {'py2exe': OPTIONS},zipfile = None,windows=[{'script': '%s.py' %(main_script)}]) 

data_files = [ 
    ('template', 'D:/Program Files (x86)/Python27/Lib/site-packages/docx-template/*'), 
] 

setup(
    options={'py2exe': OPTIONS}, 
    zipfile=None, 
    windows=[{'script': '%s.py' %(main_script)}], 
    data_files=data_files 
) 

在模板文件都可能是錯誤的上面的確切地點,所以你可能需要調整。

但是可能還需要包含其他幾組data_files。您可能想要使用os.listdiros.walk命令類型以編程方式檢索它們。

正如在其他文章中提到,你也將不得不改變

bundle_parameter=1 

bundle_parameter=2 

在文件的頂部。

+0

您可以發佈您的編輯到我上面發佈的設置代碼嗎? – user699540 2012-04-18 19:47:14

+0

@ user699540我希望我的新解釋能讓你走向正確的道路。 py2exe是一個總PITA。 – mayhewr 2012-04-18 20:49:48

+0

我試過沒有運氣。 – user699540 2012-04-19 16:27:31

0

您可以使用基於python-docxthis API來解決整個問題。該API的優點是,這個沒有savedoc功能,所以你不會有任何其他的AssertionError

對於WindowsError: [Error 3] The system cannot find the path specified: 'D:\\docx_example\\docx_example.exe\\template'錯誤,你需要編輯api.py文件,該文件位於系統的Python的文件夾的docx蛋夾(在我的電腦:C:\Python27\Lib\site-packages\python_docx-0.3.0a5-py2.7.egg\docx

更改此:

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

對此:

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

第一個是取實際運行的程序並將其添加到路徑中以定位templates文件夾。
C:\myfiles\myprogram.exe\templates\default.docx

該解決方案只採用路徑,而不是正在運行的程序。
C:\myfiles\templates\default.docx

希望它有幫助!

0

而是改變某些庫文件的,我覺得它更容易和更清潔告訴蟒蛇,DOCX明確到哪裏尋找模板,即:

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

這有效地解決了py2exe和DOCX路徑問題。

0

我已經找到了解決

在api.py

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

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

或任何你的docx文件是

相關問題