Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql.connector bug during "except" when compiled with pyinstaller?

I have a python program which makes mysql calls that I build into an exe using pyinstaller. The following problem occurs with either a --onefile or a --onedir compile using pyinstaller.

I have been able to use either mysqldb or mysql.connector to successfully connect and make queries.

Here is the mysqldb connect logic:

# from http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
try:
    db = MySQLdb.connect(host=hostname,user=username,passwd=password)
except MySQLdb.Error as e:
    reply = QtGui.QMessageBox.critical(self, "Error",str(e.args[1]))            
    return 

Here is the mysql.connector connect logic:

# http://dev.mysql.com/
try:
    db = mysql.connector.connect(host=hostname,user=username,password=password)
except mysql.connector.Error as e:   
    reply = QtGui.QMessageBox.critical(self, "Error",str(e.msg))
    return

If I provide a bad host address then an "except" is thrown during both connect calls and the error message is trapped and displayed. This works correctly for both connectors before I compile with pyinstaller.

However, the mysql.connector "except" does not occur in the compiled version of my program. The "except" does work correctly for the mysqldb connect call and the error message appears.

This leads me to conclude that mysql.connector has a bug. Can anyone else confirm this or am I doing something wrong?

like image 242
panofish Avatar asked May 14 '14 14:05

panofish


1 Answers

All these tools (pyinstaller,py2app,py2exe) do not support try/except the way you think.

The code generated has (well should have) both try and except clauses, but for the purposes of inferring which modules are actually needed by the program, only one branch is evaluated.

This may wreak all sorts of havoc with dynamic loading.

The simple, hackish fix is to include all the relevant imports directly, for example:

import mysql
import mysql.connector
import mysql.secret_lazy_loaded_submodule
import QtGui
import QtGui.QMessageBox
import QtGui.secret_lazy_loaded_submodule
try:
    mysql.connector.foo()
except Exception:
    QtGui.QMessageBox.foo()
like image 74
Dima Tisnek Avatar answered Sep 20 '22 03:09

Dima Tisnek