制作执行另一个 python 代码的 python 代码的单个 exe 文件

Making single exe file of python code which executes another python code

我是 Tkinter 的新手,我编写了一个非常简单的 Tkinter 代码,它从用户那里获取两个输入,然后使用 os.system 执行另一个 python 脚本,并将两个输入作为参数传递。该代码基本上找出了 CSV 文件中的差异。

分享下面的Tkinter代码。

import tkinter as tk
import os
def csv_diff():
    global first
    first = e1.get().replace('\','\\')
    second = e2.get().replace('\','\\')
    execute = 'python' +' '+'File_diff.py' + ' ' +first+' '+second
    os.system(execute)

root = tk.Tk()
root.geometry("400x200")
root.configure(bg='green')
window = tk.Label(root,bg = "yellow", text="File Difference").grid(row=0)
tk.Label(root, text="1st CSV Location").grid(row=1)
tk.Label(root, text="2nd CSV Location").grid(row=2)
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e1.grid(row=1, column=1)
e2.grid(row=2, column=1)
slogan = tk.Button(root,text="Run",command=csv_diff).grid(row=3, column=1, sticky=tk.W,pady=4)
root.mainloop()

第二个密码File_diff.py是

import sys
first_file_path = sys.argv[1]
second_file_path = sys.argv[2]
with open(first_file_path, 'r') as t1, open(second_file_path, 'r') as t2:
    fileone = t1.readlines()
    filetwo = t2.readlines()
with open('update.csv', 'a') as outFile:
    outFile.write(fileone[0])
with open('update.csv', 'a') as outFile:
    for line in filetwo:
        if line not in fileone:
            outFile.write(line)
with open('update.csv', 'a') as outFile:
    for line in fileone:
        if line not in filetwo:
            outFile.write(line)

现在我想为这些程序制作一个可执行文件。 我尝试使用 pyinstaller 但随后显示错误,即没有文件 File_diff.py 不存在。

我无法理解如何为这两个代码制作一个 exe 文件。 谁能解释一下如何为此制作单个可执行文件?

您需要将 File_diff.py 包含到生成的可执行文件中:

pyinstaller -F --add-data File_diff.py;. my_script.py

由于打包到生成的可执行文件中的所有文件都将在 运行 可执行文件时提取到临时目录,因此您的代码需要获取临时目录才能访问这些文件:

import os
import sys
...

# function to get the path of a resource
def get_resource(resource):
    resource_path = getattr(sys, "_MEIPASS", "")
    return os.path.join(resource_path, resource)

然后你可以像下面这样执行外部脚本:

def csv_diff():
    first = e1.get().replace('\','\\')
    second = e2.get().replace('\','\\')
    execute = ' '.join(['python', get_resource('File_diff.py'), first, second])
    os.system(execute)