2016-12-01 75 views
0

我已經編寫了一個Python程序來分別備份MySQL db的所有對象。該程序在我的機器上運行時工作正常,但是當我使用cx_freeze創建可執行文件時,它無法在另一臺機器上運行。 我發現錯誤的原因是配置的文本文件。當我不寫配置文件時,程序運行良好,否則會出錯。Python:無法運行由cx_freeze創建的Python可執行文件(帶有文本文件)

我的提取代碼: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文件

[setup.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 

回答

0

這已檢測到問題,並在源代碼庫已經解決了。問題是使用相對路徑啓動可執行文件時所做的os.chdir()調用。您有三種選擇現在:

  • 使用絕對路徑啓動可執行
  • 獲得更新的來源和構建它(那麼你可以使用相對路徑)
  • 等待cx_Freeze的下一版本(希望很快!)
+0

雖然我會嘗試絕對路徑,我可以在另一個選擇。我不確定它的原因。 因此,我在更改父文件夾中的目錄之前創建了臨時文本文件,然後在最後刪除相同的文件。這解決了問題,而不使用絕對路徑。但感謝解決方案。 –

+0

今天發佈了cx_Freeze(5.0.1)的下一個版本,並解決了此問題。 –

相關問題