PyInstaller 和 python-docx 模块不能一起工作 [英] PyInstaller and python-docx module do not work together

查看:41
本文介绍了PyInstaller 和 python-docx 模块不能一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作我的程序的可执行文件以提供给我的 FTC 团队.一切正常,但是当我尝试使用包含 python-docx 的脚本时,它并没有完成整个过程.当我在 PyCharm 和终端中运行它时,它可以工作.这是代码.我有python3.

from tkinter import *导入系统、数学、随机、日期时间、操作系统、时间导入 tkinter.messagebox从 tkinter 导入文件对话框从 tkinter.filedialog 导入 askopenfilename从 tkinter.messagebox 导入 showerror从时间导入 gmtime, strftime从 docx 导入文档从 docx.shared 导入英寸导入 xlsxwriter导出 = "Excel"工作 = "没有工作"current_time = strftime("%m-%d-%Y", gmtime())根 = Tk()文本区域 = 文本(宽度=60,高度=17,pady=0)任务 = 条目(宽度 = 90)任务.插入(10,任务:")e1 = 条目()e1.insert(10, "名字")e2 = 条目()e2.insert(10, "姓氏")TextArea.insert(END, "反射:")title = [Titan Tech"、Caleb Fahlgren 创造了这个!"、Python 就是生命!"、FIRST Robotics!"、这个程序有 200 多行代码!"]标题 = (random.choice(title))root.title(标题)root.geometry("680x600")#提交按钮#这个定义写入excel文件定义提交():submit = tkinter.messagebox.askquestion("提交条目", "您确定要提交吗?")如果提交==是":current_time = strftime("%m-%d-%Y %H:%M", gmtime())全名 = "%s %s" % (e1.get(), e2.get())姓氏 = "%s" % (e2.get())task1 = "%s" % (task.get())alltext = TextArea.get("1.0",END)workbook = xlsxwriter.Workbook('Titan Tech' + (strftime("%m-%d-%Y", gmtime())) + '.xlsx')工作表 = workbook.add_worksheet()format_text = workbook.add_format()format_text.set_text_wrap()cell_format = workbook.add_format({'align': 'center','valign': 'vcenter','border': 1,'text_wrap': 1})middle = workbook.add_format({'align':'center'})worksheet.merge_range('A5:G20', "", cell_format)worksheet.merge_range('A4:G4', "", cell_format)粗体 = workbook.add_format({'bold': 1})worksheet.write('A1', 'Name:',bold)worksheet.write('A4', task1)worksheet.write_string('B1',全名, 粗体)worksheet.merge_range('A2:B2', "", cell_format)worksheet.merge_range('D2:E2', "", cell_format)worksheet.write_string('A2',"学生姓名缩写")worksheet.write_string('C2',"___",middle)worksheet.write_string('D2',"导师姓名缩写")worksheet.write_string('F2',"___",middle)worksheet.write('E1', 'Date:',bold)worksheet.write('F1',(strftime("%m-%d-%Y", gmtime())),bold)worksheet.write_rich_string('A5',alltext,cell_format)userconfirm = tkinter.messagebox.showinfo("Save","您的条目已保存到" + export + " 文档!")workbook.close()定义重置():python = sys.executableos.execl(蟒蛇,蟒蛇,* sys.argv)定义按键(事件):如果 event.keysym == 'Escape':root.destroy()定义退出():quitask = tkinter.messagebox.askquestion("退出", "你确定要退出吗?")如果 quitask == 是":root.destroy()firstname = Label(root, text="First Name",font=("Helvetica", 12),fg="green")lastname = Label(root, text="Last Name",font=("Helvetica", 12),fg="green")time = Label(root, text=current_time, font=("Helvetica", 12),fg="black")滚动条 = 滚动条(根)ScrollBar.config(command=TextArea.yview)TextArea.config(yscrollcommand=ScrollBar.set)ScrollBar.pack(side=RIGHT, fill=Y)定义 cf():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "名称 1")定义():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "名称 2")定义厘米():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 3")定义 np():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "名称 4")定义cp():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 5")定义 ns():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 6")def ct():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 7")定义 kt():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 8")定义 mt():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 9")def ek():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "样本")e2.insert(10, "姓名 10")定义 n():e1.delete(0, 'end')e2.delete(0, 'end')e1.insert(10, "团队")e2.insert(10, "姓名")定义其他():e1.delete(0, 'end')e2.delete(0, 'end')定义文本文件():current_time = strftime("%m-%d-%Y", gmtime())全名 = "%s %s" % (e1.get(), e2.get())姓氏 = "%s" % (e2.get())task1 = "%s" % (task.get())alltext = TextArea.get("1.0",END)textfile1 = tkinter.messagebox.askquestion("文本文件", "您确定要导出为文本文件吗?")如果 textfile1 == 是":textfile = open('Titan Tech' + (strftime("%m-%d-%Y", gmtime())) + '.txt',"w")textfile.write("Titan Tech | Team #10385")textfile.write("姓名:" + 全名)textfile.write(" " + "日期:" + current_time)textfile.write('
' + '
' + task1)textfile.write('
' + '
' + alltext)textfile.close()tkinter.messagebox.showinfo("Save", "您已成功导出到文本文件.它在此程序的位置.")def helpmenusave():helpaveconfirm = tkinter.messagebox.showinfo("Save", "此程序将 Excel、World 或文本文档导出到此程序所在的位置!")定义用户界面菜单():helpuserinterface = tkinter.messagebox.showinfo("用户界面", "用户选项卡是你可以点击你的名字来自动填充名称文本框的地方.导出选项卡是你选择导出为特定格式的地方.")定义打开():textopen = tkinter.filedialog.askopenfile(mode='r', filetypes=[('Text Files', '*.txt'),('All Files', '*')])如果 textopen != 无:txtopen = textopen.read()TextArea.delete(1.0,END)TextArea.insert(END,txtopen)tkinter.messagebox.showinfo("打开", "成功!")尝试:txtopen.close()除了属性错误:打印(属性错误")菜单栏 = 菜单(根)文件菜单 = 菜单(菜单栏,撕纸 = 0)filemenu.add_command(label="New",command=Reset)filemenu.add_command(label="Open",command=Open)filemenu.add_command(label="Exit",command=Quit)menubar.add_cascade(label="File",menu=filemenu)#帮助菜单helpmenu = Menu(menubar,tearoff = 0)helpmenu.add_command(label="None", command=n)helpmenu.add_command(label="样本名称 1", command=cf)helpmenu.add_command(label="样本名称 2", command=al)helpmenu.add_command(label="样品名称 3", command=cm)helpmenu.add_command(label="样本名称 4", command=np)helpmenu.add_command(label="样本名称 5",command=cp)helpmenu.add_command(label="样本名称 6",command=ns)helpmenu.add_command(label="样本名称 7",command=ct)helpmenu.add_command(label="样本名称 8",command=kt)helpmenu.add_command(label="样本名称 9",command=mt)helpmenu.add_command(label="样本名称 10", command=ek)helpmenu.add_command(标签=其他",命令=其他)menubar.add_cascade(label="Users",menu=helpmenu)

这就是问题所在.它适用于 Pycharm 和终端,但是当我使用 PyInstaller 编译它时,它只执行 wordsaveask = tkinter.messagebox.askquestion 行,但在其下没有任何内容.它应该创建 Word 文件,但没有.我也没有收到任何错误消息.

def Word():current_time = strftime("%m-%d-%Y", gmtime())姓氏 = "%s" % (e2.get())全名 = "%s %s" % (e1.get(), e2.get())task1 = "%s" % (task.get())alltext = TextArea.get("1.0",END)wordsaveask = tkinter.messagebox.askquestion("Save", "您确定要导出到 Microsoft Word 文件吗?")如果 wordsaveask == ("yes") :文档 = 文档()document.add_heading('FTC Titan Tech Summary', 0)document.add_paragraph('Titan Tech | Team #10385')document.add_paragraph('导师姓名首字母 ____ 学生姓名首字母 _____')document.add_paragraph('姓名:' + 全名)document.add_paragraph('日期:' + current_time)document.add_paragraph(task1)document.add_paragraph(alltext)document.save('泰坦科技' + (strftime("%m-%d-%Y", gmtime())) + '.docx')tkinter.messagebox.showinfo('Save', '程序已将信息导出到 Microsoft Word 文档中!')#出口导出菜单 = 菜单(菜单栏,撕下 = 0)exportmenu.add_command(label="Microsoft Excel",command=Submit)exportmenu.add_command(label="Microsoft Word",command=Word)exportmenu.add_command(label="文本文件",command=TextFile)menubar.add_cascade(label="Export",menu=exportmenu)帮助菜单 = 菜单(菜单栏,撕下 = 0)helpmenu.add_command(label="保存帮助", command=helpmenusave)helpmenu.add_command(label="用户界面", command=userinterfacemenu)menubar.add_cascade(label="Help",menu=helpmenu)root.config(菜单=菜单栏)Submit = Button(root, fg="white", bg="green", text="Submit", width=50, command=Submit, activebackground="yellow")Quit = Button(root, fg="white", bg="green", text="Quit", width=50, command=Quit,activebackground="yellow")root.bind_all('', 按键)名字.pack()e1.pack()姓氏.pack()e2.pack()时间.pack()任务.pack()TextArea.pack(expand=YES, fill=BOTH)提交.pack()退出.pack()主循环()

解决方案

Pyinstaller 不包含 docx 模块(我有同样的问题,我会写给其他人,因为我找不到如何修复它的正确教程)

如果你在 cmd 中安装了 Pyinstaller:

pyi-makespec your_py_file_name.py

此命令会创建 .spec 文件,但不会继续构建可执行文件.

在记事本中打开 .spec 文件并通过添加:

导入系统从操作系统导入路径site_packages = next(p for p in sys.path if 'site-packages' in p)

datas=[(path.join(site_packages,"docx","templates"), "docx/templates")],

我的示例 .spec 文件看起来像这样

# -*- 模式:python -*-导入系统从操作系统导入路径site_packages = next(p for p in sys.path if 'site-packages' in p)block_cipher = 无a = Analysis(['xml_reader.py'],pathex=['C:\Users\Lenovo\Desktop\exe'],二进制文件=[],datas=[(path.join(site_packages,"docx","templates"),"docx/模板")],隐藏进口=[],钩子路径=[],runtime_hooks=[],排除=[],win_no_prefer_redirects=假,win_private_assemblies=假,密码=块_密码)pyz = PYZ(a.pure, a.zipped_data,密码=块_密码)exe = EXE(pyz,a. 脚本,exclude_binaries=真,名称='xml_reader',调试=假,条=假,upx=真,控制台=真)coll = COLLECT(exe,a.二进制文件,a.zip 文件,a.数据,条=假,upx=真,名称='xml_reader')

在cmd中生成exe文件类型

pyinstaller your_py_file_name.spec

它应该生成你的可执行文件所在的 dist 文件夹

I am trying to make an executable of my program to give to my FTC team. Everything works but when I try to use my script that includes python-docx in it but it does not complete the whole thing. It works when I run it in PyCharm and from the terminal. Here is the code. I have python3.

from tkinter import *
import sys,math,random,datetime,os,time
import tkinter.messagebox
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from time import gmtime, strftime
from docx import Document
from docx.shared import Inches
import xlsxwriter

export = "Excel"
job = "No Job"
current_time = strftime("%m-%d-%Y", gmtime())
root = Tk()

TextArea = Text(width=60,height=17,pady=0)
task = Entry(width=90)
task.insert(10, "Task:")
e1 = Entry()
e1.insert(10, "First Name")
e2 = Entry()
e2.insert(10, "Last Name")
TextArea.insert(END, "Reflection:")
title = ["Titan Tech ", "Caleb Fahlgren made this!", "Python is life!", "FIRST Robotics!","This program is over 200 lines of code!"]
title = (random.choice(title))
root.title(title)
root.geometry("680x600")

#Submit Button
#This definition writes to the excel file
def Submit():
    submit = tkinter.messagebox.askquestion("Submit Entry", "Are you sure you want to submit?")
    if submit == "yes":
        current_time = strftime("%m-%d-%Y %H:%M", gmtime())
        fullname = "%s %s" % (e1.get(), e2.get())
        lastname = "%s" % (e2.get())
        task1 = "%s" % (task.get())
        alltext = TextArea.get("1.0",END)
        workbook = xlsxwriter.Workbook('Titan Tech ' + (strftime("%m-%d-%Y", gmtime())) + '.xlsx')
        worksheet = workbook.add_worksheet()
        format_text = workbook.add_format()
        format_text.set_text_wrap()
        cell_format = workbook.add_format({'align': 'center','valign': 'vcenter','border': 1,'text_wrap': 1})
        middle = workbook.add_format({'align':'center'})
        worksheet.merge_range('A5:G20', "", cell_format)
        worksheet.merge_range('A4:G4', "", cell_format)
        bold = workbook.add_format({'bold': 1})
        worksheet.write('A1', 'Name:',bold)
        worksheet.write('A4', task1)
        worksheet.write_string('B1',fullname, bold)
        worksheet.merge_range('A2:B2', "", cell_format)
        worksheet.merge_range('D2:E2', "", cell_format)
        worksheet.write_string('A2',"Student Initials")
        worksheet.write_string('C2',"_______",middle)
        worksheet.write_string('D2',"Mentor Initials")
        worksheet.write_string('F2',"_______",middle)
        worksheet.write('E1', 'Date:',bold)
        worksheet.write('F1',(strftime("%m-%d-%Y", gmtime())),bold)
        worksheet.write_rich_string('A5',alltext ,cell_format)
        userconfirm = tkinter.messagebox.showinfo("Save","Your entry has been saved to an " + export + " document!")
        workbook.close()

def Reset():
    python = sys.executable
    os.execl(python, python, * sys.argv)

def keypress(event):
    if event.keysym == 'Escape':
        root.destroy()

def Quit():
    quitask = tkinter.messagebox.askquestion("Quit", "Are you sure you want to quit?")
    if quitask == "yes":
        root.destroy()


firstname = Label(root, text="First Name",font=("Helvetica", 12),fg="green")
lastname = Label(root, text="Last Name",font=("Helvetica", 12),fg="green")
time = Label(root, text=current_time, font=("Helvetica", 12),fg="black")

ScrollBar = Scrollbar(root)
ScrollBar.config(command=TextArea.yview)
TextArea.config(yscrollcommand=ScrollBar.set)
ScrollBar.pack(side=RIGHT, fill=Y)


def cf():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 1")
def al():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 2")
def cm():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 3")
def np():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 4")
def cp():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 5")
def ns():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 6")
def ct():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 7")
def kt():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 8")
def mt():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 9")
def ek():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Sample")
    e2.insert(10, "Name 10")
def n():
    e1.delete(0, 'end')
    e2.delete(0, 'end')
    e1.insert(10, "Team")
    e2.insert(10, "Name")
def other():

    e1.delete(0, 'end')
    e2.delete(0, 'end')

def TextFile():
    current_time = strftime("%m-%d-%Y", gmtime())
    fullname = "%s %s" % (e1.get(), e2.get())
    lastname = "%s" % (e2.get())
    task1 = "%s" % (task.get())
    alltext = TextArea.get("1.0",END)
    textfile1 = tkinter.messagebox.askquestion("Text File", "Are you sure you want to export as a text file?")
    if textfile1 == "yes":
        textfile = open('Titan Tech' + (strftime("%m-%d-%Y", gmtime())) + '.txt',"w")
        textfile.write("Titan Tech  | Team # 10385   ")
        textfile.write("Name: " + fullname)
        textfile.write("        " + "Date: " + current_time)
        textfile.write('
' + '
' + task1)
        textfile.write('
' + '
' + alltext)
        textfile.close()
        tkinter.messagebox.showinfo("Save", "You have exported to text file successfully. It is in the location of this program.")

def helpmenusave():
    helpsaveconfirm = tkinter.messagebox.showinfo("Save", "This program exports the Excel, World, or text document to the location of this program!")

def userinterfacemenu():
    helpuserinterface = tkinter.messagebox.showinfo("User Interface", "The Users tab is where you can click on your name to autofill the name text boxes. The Export tab is where you choose to export to a specific format.")

def Open():
    textopen = tkinter.filedialog.askopenfile(mode='r', filetypes=[('Text Files', '*.txt'),('All Files', '*')])
    if textopen != None:
        txtopen = textopen.read()
        TextArea.delete(1.0,END)
        TextArea.insert(END,txtopen)
        tkinter.messagebox.showinfo("Open",  "Success!")
        try:
            txtopen.close()
        except AttributeError:
            print("Attribute Error")

menubar = Menu(root)
filemenu = Menu(menubar,tearoff = 0)
filemenu.add_command(label="New",command=Reset)
filemenu.add_command(label="Open",command=Open)
filemenu.add_command(label="Exit",command=Quit)
menubar.add_cascade(label="File",menu=filemenu)

#help menu
helpmenu = Menu(menubar,tearoff = 0)
helpmenu.add_command(label="None", command=n)
helpmenu.add_command(label="Sample Name 1", command=cf)
helpmenu.add_command(label="Sample Name 2", command=al)
helpmenu.add_command(label="Sample Name 3", command=cm)
helpmenu.add_command(label="Sample Name 4", command=np)
helpmenu.add_command(label="Sample Name 5",command=cp)
helpmenu.add_command(label="Sample Name 6",command=ns)
helpmenu.add_command(label="Sample Name 7",command=ct)
helpmenu.add_command(label="Sample Name 8",command=kt)
helpmenu.add_command(label="Sample Name 9",command=mt)
helpmenu.add_command(label="Sample Name 10", command=ek)
helpmenu.add_command(label="Other", command=other)
menubar.add_cascade(label="Users",menu=helpmenu)

This is where the problem is. It works in Pycharm and in terminal but when I compile it with PyInstaller it only does the wordsaveask = tkinter.messagebox.askquestion line but nothing under it. It is supposed to create the Word file but doesn't. I also don't get any error messages.

def Word():
    current_time = strftime("%m-%d-%Y", gmtime())
    lastname = "%s" % (e2.get())
    fullname = "%s %s" % (e1.get(), e2.get())
    task1 = "%s" % (task.get())
    alltext = TextArea.get("1.0",END)
    wordsaveask = tkinter.messagebox.askquestion("Save", "Are you sure you want to export to a Microsoft Word file?")
    if wordsaveask == ("yes") :
        document = Document()
        document.add_heading('FTC Titan Tech Summary', 0)
        document.add_paragraph('Titan Tech  | Team # 10385')
        document.add_paragraph('Mentor Initials ____           Student Initials _____')
        document.add_paragraph('Name: ' + fullname)
        document.add_paragraph('Date: ' + current_time)
        document.add_paragraph(task1)
        document.add_paragraph(alltext)
        document.save('Titan Tech ' + (strftime("%m-%d-%Y", gmtime())) + '.docx')
        tkinter.messagebox.showinfo('Save', 'The program has exported the information to a Microsoft Word document!')

#export 
exportmenu = Menu(menubar, tearoff = 0)
exportmenu.add_command(label="Microsoft Excel",command=Submit)
exportmenu.add_command(label="Microsoft Word",command=Word)
exportmenu.add_command(label="Text File",command=TextFile)
menubar.add_cascade(label="Export",menu=exportmenu)

helpmenu = Menu(menubar, tearoff = 0)
helpmenu.add_command(label="Save Help", command=helpmenusave)
helpmenu.add_command(label="User Interface", command=userinterfacemenu)
menubar.add_cascade(label="Help",menu=helpmenu)
root.config(menu=menubar)

Submit = Button(root, fg="white", bg="green", text="Submit", width=50, command=Submit, activebackground="yellow")
Quit = Button(root, fg="white", bg="green", text="Quit", width=50, command=Quit,activebackground="yellow")

root.bind_all('<Key>', keypress)
firstname.pack()
e1.pack()
lastname.pack()
e2.pack()
time.pack()
task.pack()
TextArea.pack(expand=YES, fill=BOTH)
Submit.pack()
Quit.pack()
mainloop()

解决方案

Pyinstaller doesn't include docx modules(I had the same problem, i will write it for others because i couldnt find proper tutorial how to fix it)

If you have Pyinstaller installed use in cmd:

pyi-makespec your_py_file_name.py

This command creates .spec file but does not go on to build the executable.

Open .spec file in Notepad and edit it by adding:

import sys
from os import path
site_packages = next(p for p in sys.path if 'site-packages' in p)

And

datas=[(path.join(site_packages,"docx","templates"), "docx/templates")],

My example .spec file looks like this

# -*- mode: python -*-

import sys
from os import path
site_packages = next(p for p in sys.path if 'site-packages' in p)
block_cipher = None


a = Analysis(['xml_reader.py'],
             pathex=['C:\Users\Lenovo\Desktop\exe'],
             binaries=[],
             datas=[(path.join(site_packages,"docx","templates"), 
"docx/templates")],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='xml_reader',
          debug=False,
          strip=False,
          upx=True,
          console=True )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='xml_reader')

To make exe file type in cmd

pyinstaller your_py_file_name.spec

It should produce dist folder where is your executable

这篇关于PyInstaller 和 python-docx 模块不能一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆