gpt4 book ai didi

Python:无法运行 cx_freeze 创建的 Python 可执行文件(带有文本文件)

转载 作者:行者123 更新时间:2023-11-29 19:47:35 25 4
gpt4 key购买 nike

我编写了一个Python程序来单独备份MySQL数据库的所有对象。该程序在我的机器上运行时工作正常,但是当我使用 cx_freeze 创建可执行文件时,它无法在另一台机器上运行。我发现错误的原因是配置的文本文件。当我不写配置文件时,程序运行正常,否则会出错。

我的提取代码:mysql_extractor.py。请查看filter_parsing函数,它可能是错误的来源。

[mysql_extractor.py]

#!/usr/bin/env python3

"""
__title__ = "mysql_extractor.py"
__description__ = "Script to extract objects of MySQL database individually"

"""

from __future__ import print_function
import argparse
import os
import sys
import pymysql
import encodings.idna

class MySQLExtractor:

############################################
#
# PUBLIC METHODS
#
############################################

directory = ""
dumpcmd = ""

def parse_argument(self):
self.parser = argparse.ArgumentParser(description="MySQL dump process")
args_conn = self.parser.add_argument_group(title="Database Connection")
args_conn.add_argument('--host', dest="hostname", default="127.0.0.1", help="Host name or IP Address")
args_conn.add_argument('-u', '--username', dest="username", default="root", help="Database user name.")
args_conn.add_argument('--password', dest="password", default="", help="Password for the given user.")
args_conn.add_argument('-d', '--db', dest="db", default="test", help="Database name to connect to.")

args_filter = self.parser.add_argument_group(title="Filters", description="All object names given in any filter MUST be fully schema qualified.")
args_filter.add_argument('--gettables', dest="gettables", action="store_true", help="Get all tables only")

self.args = self.parser.parse_args()
# end _parse_arguments()

def gettables(self):
try:
print ("Dumping Tables..")
conn = pymysql.connect(host=self.args.hostname, user=self.args.username, passwd=self.args.password, database=self.args.db)
cursor = conn.cursor()
if not os.path.exists("tables"):
os.makedirs("tables")
os.chdir("tables")
query = "show full tables where Table_Type != 'VIEW'"
cursor.execute(query)
for row in cursor:
dumpcmd = self.dumpcmd
dumpcmd += " " + row[0] + " --no-data > " + row[0] + ".sql"
os.system(dumpcmd)
os.chdir(self.directory)
cursor.close()
conn.close()
except pymysql.Error as e:
print("Error lin connecting to the DB: " + str(e) )
sys.exit(2)
# end gettables

def filter_parsing(self):
"""
Some more code here, but not relevant to the question
"""
self.directory = self.args.db
os.makedirs(self.directory)
os.chdir(self.directory)

# Create config file <Probable source of error>
filename = "my_config"
f = open(filename, 'w')
f.write("[mysqldump]\n")
f.write("host='"+ self.args.hostname + "'\n")
f.write("user='"+ self.args.username + "'\n")
f.write("password='"+ self.args.password + "'\n")
f.close()

self.directory = os.getcwd()
self.dumpcmd = "mysqldump --defaults-file=" + self.directory + "/my_config" +" --skip-dump-date " + self.args.db

# If the following command is used and config file is not created, it gives no error.
# self.dumpcmd = "mysqldump -u " + self.args.username + " -h " + self.args.hostname + " --password=" + self.args.password + " --skip-dump-date " + self.args.db

#gettables is selected
if self.args.gettables==True:
self.gettables()
return
# end filter_parsing

#end class MySQLExtractor


p = MySQLExtractor()
p.parse_argument()
try:
p.filter_parsing()
finally:
print ("Done")

这段代码在我的机器上运行时工作正常。但是当我创建一个可执行文件并在其他计算机上运行它时,它会出现错误。这是我的 setup.py 文件

[设置.py]

import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os","MySQLdb"], "excludes": ["tkinter"]}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"

setup( name = "extractor",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [Executable("mysql_extractor.py", base=base)])

抛出的错误是:

Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible
File "/usr/lib64/python3.4/site-packages/cx_Freeze-5.0-py3.4-linux-x86_64.egg/cx_Freeze/initscripts/__startup__.py", line 12, in <module>
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible
File "/usr/lib64/python3.4/site-packages/cx_Freeze-5.0-py3.4-linux-x86_64.egg/cx_Freeze/initscripts/Console.py", line 21, in <module>
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1191, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1161, in _load_backward_compatible
File "/home/AD/abhishek.bhola/Documents/tmp/tmp_test.py", line 97, in <module>
File "/home/AD/abhishek.bhola/Documents/tmp/tmp_test.py", line 74, in filter_parsing
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2222, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 2164, in _find_spec
File "<frozen importlib._bootstrap>", line 1940, in find_spec
File "<frozen importlib._bootstrap>", line 1916, in _get_spec
File "<frozen importlib._bootstrap>", line 1897, in _legacy_get_spec
File "<frozen importlib._bootstrap>", line 863, in spec_from_loader
File "<frozen importlib._bootstrap>", line 904, in spec_from_file_location
OSError: zipimport: can not open file ./lib64/python34.zip

最佳答案

此问题已在源存储库中检测到并已解决。问题是使用相对路径启动可执行文件时进行的 os.chdir() 调用。您现在有三个选择:

  • 使用绝对路径来启动可执行文件
  • 获取更新的源代码并构建它(然后您可以使用相对路径)
  • 等待 cx_Freeze 的下一个版本发布(希望很快!)

关于Python:无法运行 cx_freeze 创建的 Python 可执行文件(带有文本文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com