Archivio

Archivio per la categoria ‘py2exe’

py2exe: matplotlib

5 Luglio 2011 Commenti chiusi

Avendo a che fare con matplotlib, ho avuto parecchi problemi a configurare il setup di py2exe.
Grazie alla doc ufficiale di py2exe con qualche piccolo accorgimento, sono
riuscito a fare il freeze della mia applicazione.

Riassumo il tutto estrapolando solo la parte inerente Matplotlib:

'''Module for HistoGram creation'''

import numpy as np
import matplotlib
matplotlib.use('wxagg') # backend

import matplotlib.pyplot as plt


class Bars(object):
    '''Crea un istogramma in base ai dati in ingresso:
           possono essere di tipo dict(nome: valore) o
           di tipo list, con il formato tipico
           del metodo fetchall() d sqlite3
    ''' 

    def __init__(self, data):
        self.data = data
        self.dict_data = {}
        print "HISTO > Loading data... ", self.data
        for item in self.data:
            self.dict_data[item[0]] = (item[1])
        try:
            n_bars = len(self.dict_data)
            pts = self.dict_data.values()
            teams = self.dict_data.keys()
            ind = np.arange(n_bars)     # the x locations for bar
            width = 0.2                 # the width of the bars
            plt.subplot(111)
            
            bars = plt.bar(ind + 0.2, pts, width, color='b', align = 'center')
            
            plt.title('Classifica')
            plt.ylabel('pts')
            plt.xticks(ind + width , teams, size = 'x-small', rotation = 15)
            
            for vbar in bars:
                val = float(vbar.get_height())
                x_pos = vbar.get_x() + 0.4
                y_pos = vbar.get_height() - 0.1 * vbar.get_height()
                plt.text(x_pos, y_pos, '%.1f'%val, ha='center', va='bottom',
                         size = 'small', rotation = 90)
            plt.show()
        
        except AttributeError:
            print "Grafico non rappresentabile, controllare dato in ingresso"

def main():
    '''app starter'''
    data = [('Boy SAN', 100), ('Cioppersson', 105),
            ('Stella Blu Kativeria', 120), ('Pippo', 180),
            ('MiddleSboron', 98), ('Nizzi', 140), ('F.C.Zipangolo', 165),
            ('Real Ancona', 135), ('Gnagna', 88), ('Cento', 98)]
    Bars(data)
if __name__ == '__main__':
    main()

Dal solito sample del setup di py2exe:

#!/usr/bin/python
"""py2exe custom setup Sample
author: bancaldo"""

import py2exe, sys, wx, os, glob
import matplotlib
from distutils.core import setup

if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

class FileBrowser(wx.FileDialog):
    '''Class for file browser'''
    def __init__(self):
        self.fin = None
        wildcard = "File di testo (*.py)|*.py|" 
            "Tutti i files (*.*)|*.*"
        wx.FileDialog.__init__(self, None, "scegli il file", os.getcwd(),
                               "", wildcard, wx.OPEN | wx.CHANGE_DIR)
        if self.ShowModal() == wx.ID_OK:  
            print(self.GetPath())
            self.file = self.GetPath()
            self.fin = open(self.file, 'r')
        else:
            print "operazione apertura annullata"
            self.Destroy()
        self.Destroy()

class Target(object):
    '''Terget'''
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # info di versione
        self.version = "1.0.0"
        self.company_name = "Bancaldo TM"
        self.copyright = "no copyright"
        self.name = "py2exe sample files"


def main():
    '''py2exe setup starter'''
    app = wx.PySimpleApp()
    app.MainLoop()

    manifest_template = '''
    <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
        <security>
          <requestedPrivileges>
            <requestedExecutionLevel level='asInvoker' uiAccess='false' />
          </requestedPrivileges>
        </security>
      </trustInfo>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity 
    	 type='win32' 
    	 name='Microsoft.VC90.CRT' 
    	 version='9.0.21022.8' 
    	 processorArchitecture='*' 
    	 publicKeyToken='1fc8b3b9a1e18e3b' />
        </dependentAssembly>
      </dependency>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity
             type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             processorArchitecture="*"
             publicKeyToken="6595b64144ccf1df"
             language="*" />
        </dependentAssembly>
      </dependency>
    </assembly>
    '''
    file_to_freeze = FileBrowser().file

    textentry = wx.TextEntryDialog(None, "nome file EXE?", '', '')
    if textentry.ShowModal() == wx.ID_OK:
        destname = textentry.GetValue()
    
    rt_manifest = 24
    
    explicit_incl = ["sqlalchemy.dialects.sqlite.base",
                     "matplotlib.backends.backend_wxagg",]
    other_res = [(rt_manifest, 1, manifest_template % dict(prog = "Fanta"))]

    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}
    
    test_wx = Target(description = "A GUI app",
                     script = file_to_freeze,
                     other_resources = other_res,
                     icon_resources = [(1, "images\py.ico")],
                     dest_base = destname)

    # images    
    path = (os.getcwd() + "\images\")
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]
    # matplotlib
    data_files.extend(matplotlib.get_py2exe_datafiles())

    setup(data_files = data_files, # images
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )

if __name__ == '__main__':
    main()

focalizziamo le parti importanti relative a Matplotlib:

Innanzitutto importiamo Matplotlib all’interno del setup, per poter sfruttare
la funzione get_py2exe_datafiles(), che crea un lista con tutti i file
necessari da estendere alla lista data_files.

import matplotlib
...
    # images    
    path = (os.getcwd() + "\images\")
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]
    # matplotlib
    data_files.extend(matplotlib.get_py2exe_datafiles())
...

come ultima cosa importantissima, negli “includes” espliciti da passare alle
opzioni di setup, dobbiamo aggiungere il backend utilizzato:

import matplotlib
...
    explicit_incl = ["sqlalchemy.dialects.sqlite.base",
                     "matplotlib.backends.backend_wxagg",]
...
    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}
...

link:
il mio sample,
py2exe: MatplotLib

Categorie:py2exe Tag:

py2exe: matplotlib

5 Luglio 2011 Commenti chiusi

Avendo a che fare con matplotlib, ho avuto parecchi problemi a configurare il setup di py2exe.
Grazie alla doc ufficiale di py2exe con qualche piccolo accorgimento, sono
riuscito a fare il freeze della mia applicazione.

Riassumo il tutto estrapolando solo la parte inerente Matplotlib:

'''Module for HistoGram creation'''

import numpy as np
import matplotlib
matplotlib.use('wxagg') # backend

import matplotlib.pyplot as plt


class Bars(object):
    '''Crea un istogramma in base ai dati in ingresso:
           possono essere di tipo dict(nome: valore) o
           di tipo list, con il formato tipico
           del metodo fetchall() d sqlite3
    ''' 

    def __init__(self, data):
        self.data = data
        self.dict_data = {}
        print "HISTO > Loading data... ", self.data
        for item in self.data:
            self.dict_data[item[0]] = (item[1])
        try:
            n_bars = len(self.dict_data)
            pts = self.dict_data.values()
            teams = self.dict_data.keys()
            ind = np.arange(n_bars)     # the x locations for bar
            width = 0.2                 # the width of the bars
            plt.subplot(111)
            
            bars = plt.bar(ind + 0.2, pts, width, color='b', align = 'center')
            
            plt.title('Classifica')
            plt.ylabel('pts')
            plt.xticks(ind + width , teams, size = 'x-small', rotation = 15)
            
            for vbar in bars:
                val = float(vbar.get_height())
                x_pos = vbar.get_x() + 0.4
                y_pos = vbar.get_height() - 0.1 * vbar.get_height()
                plt.text(x_pos, y_pos, '%.1f'%val, ha='center', va='bottom',
                         size = 'small', rotation = 90)
            plt.show()
        
        except AttributeError:
            print "Grafico non rappresentabile, controllare dato in ingresso"

def main():
    '''app starter'''
    data = [('Boy SAN', 100), ('Cioppersson', 105),
            ('Stella Blu Kativeria', 120), ('Pippo', 180),
            ('MiddleSboron', 98), ('Nizzi', 140), ('F.C.Zipangolo', 165),
            ('Real Ancona', 135), ('Gnagna', 88), ('Cento', 98)]
    Bars(data)
if __name__ == '__main__':
    main()

Dal solito sample del setup di py2exe:

#!/usr/bin/python
"""py2exe custom setup Sample
author: bancaldo"""

import py2exe, sys, wx, os, glob
import matplotlib
from distutils.core import setup

if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

class FileBrowser(wx.FileDialog):
    '''Class for file browser'''
    def __init__(self):
        self.fin = None
        wildcard = "File di testo (*.py)|*.py|" \
            "Tutti i files (*.*)|*.*"
        wx.FileDialog.__init__(self, None, "scegli il file", os.getcwd(),
                               "", wildcard, wx.OPEN | wx.CHANGE_DIR)
        if self.ShowModal() == wx.ID_OK:  
            print(self.GetPath())
            self.file = self.GetPath()
            self.fin = open(self.file, 'r')
        else:
            print "operazione apertura annullata"
            self.Destroy()
        self.Destroy()

class Target(object):
    '''Terget'''
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # info di versione
        self.version = "1.0.0"
        self.company_name = "Bancaldo TM"
        self.copyright = "no copyright"
        self.name = "py2exe sample files"


def main():
    '''py2exe setup starter'''
    app = wx.PySimpleApp()
    app.MainLoop()

    manifest_template = '''
    <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
        <security>
          <requestedPrivileges>
            <requestedExecutionLevel level='asInvoker' uiAccess='false' />
          </requestedPrivileges>
        </security>
      </trustInfo>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity 
    	 type='win32' 
    	 name='Microsoft.VC90.CRT' 
    	 version='9.0.21022.8' 
    	 processorArchitecture='*' 
    	 publicKeyToken='1fc8b3b9a1e18e3b' />
        </dependentAssembly>
      </dependency>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity
             type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             processorArchitecture="*"
             publicKeyToken="6595b64144ccf1df"
             language="*" />
        </dependentAssembly>
      </dependency>
    </assembly>
    '''
    file_to_freeze = FileBrowser().file

    textentry = wx.TextEntryDialog(None, "nome file EXE?", '', '')
    if textentry.ShowModal() == wx.ID_OK:
        destname = textentry.GetValue()
    
    rt_manifest = 24
    
    explicit_incl = ["sqlalchemy.dialects.sqlite.base",
                     "matplotlib.backends.backend_wxagg",]
    other_res = [(rt_manifest, 1, manifest_template % dict(prog = "Fanta"))]

    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}
    
    test_wx = Target(description = "A GUI app",
                     script = file_to_freeze,
                     other_resources = other_res,
                     icon_resources = [(1, "images\\py.ico")],
                     dest_base = destname)

    # images    
    path = (os.getcwd() + "\\images\\")
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]
    # matplotlib
    data_files.extend(matplotlib.get_py2exe_datafiles())

    setup(data_files = data_files, # images
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )

if __name__ == '__main__':
    main()

focalizziamo le parti importanti relative a Matplotlib:

Innanzitutto importiamo Matplotlib all’interno del setup, per poter sfruttare
la funzione get_py2exe_datafiles(), che crea un lista con tutti i file
necessari da estendere alla lista data_files.

import matplotlib
...
    # images    
    path = (os.getcwd() + "\\images\\")
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]
    # matplotlib
    data_files.extend(matplotlib.get_py2exe_datafiles())
...

come ultima cosa importantissima, negli “includes” espliciti da passare alle
opzioni di setup, dobbiamo aggiungere il backend utilizzato:

import matplotlib
...
    explicit_incl = ["sqlalchemy.dialects.sqlite.base",
                     "matplotlib.backends.backend_wxagg",]
...
    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}
...

link:
il mio sample,
py2exe: MatplotLib

Categorie:py2exe Tag:

Py2exe: Integrare immagini

4 Luglio 2011 2 commenti

Innanzitutto, sarebbe bene tenere le immagini relative al nostro
“programma”, tutte in una directory dedicata, nel mio caso
‘images’

Supponiamo che il “programma”, crei un frame con un bitmapButton,
il quale dovrà correttamente puntare al percorso dell’immagine,
che ingloba al suo interno:

#!/usr/bin/python
'''Simple Frame with BitmapButton'''

import wx
from wx.lib.buttons import GenBitmapTextButton

class FrameCore(wx.Frame):
    '''Initial Core Frame'''
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        panel = wx.Panel(self, wx.ID_ANY)

        self.btn_exit = GenBitmapTextButton(panel, wx.ID_ANY,
                                            wx.Bitmap('images\q.png'),
                                            'Exit'.rjust(15),
                                            (5, 5), (125, -1))
        self.btn_exit.SetBezelWidth(1)
        self.btn_exit.SetBackgroundColour('#c2e6f8')

        self.btn_exit.Bind(wx.EVT_ENTER_WINDOW, self.on_btn_enter)
        self.btn_exit.Bind(wx.EVT_LEAVE_WINDOW, self.on_btn_leave)
        self.btn_exit.Bind(wx.EVT_BUTTON, self.on_exit)

        self.Centre()
        self.Show()

    def on_btn_enter(self, event):
        '''Into Button enter-mouse event handler'''
        obj =  event.GetEventObject()
        obj.SetBackgroundColour('#ffdf85')
        obj.Refresh()

    def on_btn_leave(self, event):
        '''From Button leave-mouse event handler'''
        obj =  event.GetEventObject()
        obj.SetBackgroundColour('#c2e6f8')
        obj.Refresh()

    def on_exit(self, event):
        '''Close Frame'''
        self.Close()

def main_core(parent):
    '''Info frame starter'''
    app = wx.PySimpleApp()
    FrameCore(parent, -1, title  = 'Foo', size = (150, 100))
    app.MainLoop()
    
if __name__ == '__main__':
    main_core(parent = None)

Al momento del freeze del programma, dovremo indicare le immagini
e la directory che le conterrà, con lo stesso nome che abbiamo
usato in fase di sviluppo (‘images’):

...
    path = (&quot;c:\Documents and Settings\banchellia\workspace\rubrica\src&quot; +
            &quot;\images\&quot;)
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]

    setup(data_files = data_files,
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )
...

terminato il “freeze”, possiamo utilizzare l’eseguibile, con tanto di immagini e
nessun errore del tipo:

wx._core.PyAssertionError: C++ assertion &quot;bmp.Ok()&quot; failed at ....srcmswdib.cpp(148) in wxDIB::Create(): wxDIB::Create(): invalid bitmap

link:
il mio sample py2exepy2exe

Categorie:py2exe Tag:

Py2exe: Integrare immagini

4 Luglio 2011 Commenti chiusi

Innanzitutto, sarebbe bene tenere le immagini relative al nostro
“programma”, tutte in una directory dedicata, nel mio caso
‘images’

Supponiamo che il “programma”, crei un frame con un bitmapButton,
il quale dovrà correttamente puntare al percorso dell’immagine,
che ingloba al suo interno:

#!/usr/bin/python
'''Simple Frame with BitmapButton'''

import wx
from wx.lib.buttons import GenBitmapTextButton

class FrameCore(wx.Frame):
    '''Initial Core Frame'''
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        panel = wx.Panel(self, wx.ID_ANY)

        self.btn_exit = GenBitmapTextButton(panel, wx.ID_ANY,
                                            wx.Bitmap('images\\q.png'),
                                            'Exit'.rjust(15),
                                            (5, 5), (125, -1))
        self.btn_exit.SetBezelWidth(1)
        self.btn_exit.SetBackgroundColour('#c2e6f8')

        self.btn_exit.Bind(wx.EVT_ENTER_WINDOW, self.on_btn_enter)
        self.btn_exit.Bind(wx.EVT_LEAVE_WINDOW, self.on_btn_leave)
        self.btn_exit.Bind(wx.EVT_BUTTON, self.on_exit)

        self.Centre()
        self.Show()

    def on_btn_enter(self, event):
        '''Into Button enter-mouse event handler'''
        obj =  event.GetEventObject()
        obj.SetBackgroundColour('#ffdf85')
        obj.Refresh()

    def on_btn_leave(self, event):
        '''From Button leave-mouse event handler'''
        obj =  event.GetEventObject()
        obj.SetBackgroundColour('#c2e6f8')
        obj.Refresh()

    def on_exit(self, event):
        '''Close Frame'''
        self.Close()

def main_core(parent):
    '''Info frame starter'''
    app = wx.PySimpleApp()
    FrameCore(parent, -1, title  = 'Foo', size = (150, 100))
    app.MainLoop()
    
if __name__ == '__main__':
    main_core(parent = None)

Al momento del freeze del programma, dovremo indicare le immagini
e la directory che le conterrà, con lo stesso nome che abbiamo
usato in fase di sviluppo (‘images’):

...
    path = ("c:\\Documents and Settings\\banchellia\\workspace\\rubrica\\src" +\
            "\\images\\")
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]

    setup(data_files = data_files,
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )
...

terminato il “freeze”, possiamo utilizzare l’eseguibile, con tanto di immagini e
nessun errore del tipo:

wx._core.PyAssertionError: C++ assertion "bmp.Ok()" failed at ..\..\src\msw\dib.cpp(148) in wxDIB::Create(): wxDIB::Create(): invalid bitmap

link:
il mio sample py2exe
py2exe

Categorie:py2exe Tag:

Py2exe: errori post freeze

1 Luglio 2011 Commenti chiusi

Stavo “congelando” i sorgenti di una applicazione di prova,
con py2exe.
Ho usato questo sample:

#!/usr/bin/python
&quot;&quot;&quot;py2exe custom setup Sample
author: bancaldo&quot;&quot;&quot;

import py2exe, sys, wx, os
from distutils.core import setup

if len(sys.argv) == 1:
    sys.argv.append(&quot;py2exe&quot;)
    sys.argv.append(&quot;-q&quot;)

class FileBrowser(wx.FileDialog):
    '''Class for file browser'''
    def __init__(self):
        self.fin = None
        wildcard = &quot;File di testo (*.py)|*.py|&quot; 
            &quot;Tutti i files (*.*)|*.*&quot;
        wx.FileDialog.__init__(self, None, &quot;scegli il file&quot;, os.getcwd(),
                               &quot;&quot;, wildcard, wx.OPEN | wx.CHANGE_DIR)

        if self.ShowModal() == wx.ID_OK:  
            print(self.GetPath())
            self.file = self.GetPath()
            self.fin = open(self.file, 'r')
        else:
            print &quot;operazione apertura annullata&quot;
            self.Destroy()
        self.Destroy()

class Target(object):
    '''Terget'''
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # info di versione
        self.version = &quot;1.0.0&quot;
        self.company_name = &quot;Bancaldo TM&quot;
        self.copyright = &quot;no copyright&quot;
        self.name = &quot;py2exe sample files&quot;

def main():
    '''py2exe setup starter'''
    app = wx.PySimpleApp()
    app.MainLoop()
    manifest_template = '''
    &lt;?xml version='1.0' encoding='UTF-8' standalone='yes'?&gt;
    &lt;assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'&gt;
      &lt;trustInfo xmlns=&quot;urn:schemas-microsoft-com:asm.v3&quot;&gt;
        &lt;security&gt;
          &lt;requestedPrivileges&gt;
            &lt;requestedExecutionLevel level='asInvoker' uiAccess='false' /&gt;
          &lt;/requestedPrivileges&gt;
        &lt;/security&gt;
      &lt;/trustInfo&gt;
      &lt;dependency&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity 
    	 type='win32' 
    	 name='Microsoft.VC90.CRT' 
    	 version='9.0.21022.8' 
    	 processorArchitecture='*' 
   	 publicKeyToken='1fc8b3b9a1e18e3b' /&gt;
        &lt;/dependentAssembly&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity
             type=&quot;win32&quot;
             name=&quot;Microsoft.Windows.Common-Controls&quot;
             version=&quot;6.0.0.0&quot;
             processorArchitecture=&quot;*&quot;
             publicKeyToken=&quot;6595b64144ccf1df&quot;
             language=&quot;*&quot; /&gt;
        &lt;/dependentAssembly&gt;
      &lt;/dependency&gt;
    &lt;/assembly&gt;
    '''
    file_to_freeze = FileBrowser().file
    textentry = wx.TextEntryDialog(None, &quot;nome file EXE?&quot;, '', '')
    if textentry.ShowModal() == wx.ID_OK:
        destname = textentry.GetValue()

    rt_manifest = 24
    explicit_incl = []
    other_res = [(rt_manifest, 1, manifest_template % dict(prog = &quot;Prova&quot;))]
    setup_opts = {&quot;py2exe&quot;: {&quot;includes&quot;: explicit_incl,
                             &quot;compressed&quot;: 1,
                             &quot;optimize&quot;: 2,
                             #&quot;ascii&quot;: 1,
                             &quot;bundle_files&quot;: 1,}}
    test_wx = Target(description = &quot;A GUI app&quot;,
                     script = file_to_freeze,
                     other_resources = other_res,
                     icon_resources = [(1, &quot;py.ico&quot;)],
                     dest_base = destname)

    setup(data_files = [&quot;py.ico&quot;],
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )

if __name__ == '__main__':
    main()

La creazione dell’eseguibile è avvenuta correttamente, ma una volta eseguito il file.exe risultante, un messaggio mi avvisa di controllare il log a causa di un errore:
Mi sono trovato davanti a questa serie di messaggi

  File &quot;sqlalchemyengine__init__.pyo&quot;, line 263, in create_engine
  File &quot;sqlalchemyenginestrategies.pyo&quot;, line 50, in create
  File &quot;sqlalchemyengineurl.pyo&quot;, line 116, in get_dialect
sqlalchemy.exc.ArgumentError: Could not determine dialect for 'sqlite'.

per risolvere il problema, ci sono 2 strade:
o si inserisce un import esplicito nel file Data.py (orrido),
cioè dove si fa riferimento ad sqlalchemy

from sqlalchemy.dialects.sqlite.base import dialect

o si aggiunge il percorso del modulo contenente i dialect
negli includes del file di setup di py2exe:

explicit_incl = [&quot;sqlalchemy.dialects.sqlite.base&quot;]

Rilanciato py2exe, ho rieseguito il file.exe e di nuovo mi viene segnalato un errore.
Controllo di cosa si tratta e trovo questo nel log:

  ...
  File &quot;sqlalchemyprocessors.pyo&quot;, line 60, in to_unicode_processor_factory
  File &quot;codecs.pyo&quot;, line 930, in getdecoder
LookupError: unknown encoding: utf-8

In questo caso devo commetare l’opzione “ascii” del file di setup di py2exe

    setup_opts = {&quot;py2exe&quot;: {&quot;includes&quot;: explicit_incl,
                             &quot;compressed&quot;: 1,
                             &quot;optimize&quot;: 2,
                             #&quot;ascii&quot;: 1,
                             &quot;bundle_files&quot;: 1,}}

questo perchè la codifica “ascii” abilitata, vanifica il tentativo di utilizzo di altre codifiche (unknown encoding: utf-8)
Al terzo tentativo l’applicazione parte senza problemi.

Categorie:py2exe Tag:

Py2exe: errori post freeze

1 Luglio 2011 Commenti chiusi

Stavo “congelando” i sorgenti di una applicazione di prova,
con py2exe.
Ho usato questo sample:

#!/usr/bin/python
"""py2exe custom setup Sample
author: bancaldo"""

import py2exe, sys, wx, os
from distutils.core import setup

if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

class FileBrowser(wx.FileDialog):
    '''Class for file browser'''
    def __init__(self):
        self.fin = None
        wildcard = "File di testo (*.py)|*.py|" \
            "Tutti i files (*.*)|*.*"
        wx.FileDialog.__init__(self, None, "scegli il file", os.getcwd(),
                               "", wildcard, wx.OPEN | wx.CHANGE_DIR)

        if self.ShowModal() == wx.ID_OK:  
            print(self.GetPath())
            self.file = self.GetPath()
            self.fin = open(self.file, 'r')
        else:
            print "operazione apertura annullata"
            self.Destroy()
        self.Destroy()

class Target(object):
    '''Terget'''
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # info di versione
        self.version = "1.0.0"
        self.company_name = "Bancaldo TM"
        self.copyright = "no copyright"
        self.name = "py2exe sample files"

def main():
    '''py2exe setup starter'''
    app = wx.PySimpleApp()
    app.MainLoop()
    manifest_template = '''
    <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
        <security>
          <requestedPrivileges>
            <requestedExecutionLevel level='asInvoker' uiAccess='false' />
          </requestedPrivileges>
        </security>
      </trustInfo>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity 
    	 type='win32' 
    	 name='Microsoft.VC90.CRT' 
    	 version='9.0.21022.8' 
    	 processorArchitecture='*' 
   	 publicKeyToken='1fc8b3b9a1e18e3b' />
        </dependentAssembly>
      </dependency>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity
             type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             processorArchitecture="*"
             publicKeyToken="6595b64144ccf1df"
             language="*" />
        </dependentAssembly>
      </dependency>
    </assembly>
    '''
    file_to_freeze = FileBrowser().file
    textentry = wx.TextEntryDialog(None, "nome file EXE?", '', '')
    if textentry.ShowModal() == wx.ID_OK:
        destname = textentry.GetValue()

    rt_manifest = 24
    explicit_incl = []
    other_res = [(rt_manifest, 1, manifest_template % dict(prog = "Prova"))]
    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}
    test_wx = Target(description = "A GUI app",
                     script = file_to_freeze,
                     other_resources = other_res,
                     icon_resources = [(1, "py.ico")],
                     dest_base = destname)

    setup(data_files = ["py.ico"],
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )

if __name__ == '__main__':
    main()

La creazione dell’eseguibile è avvenuta correttamente, ma una volta eseguito il file.exe risultante, un messaggio mi avvisa di controllare il log a causa di un errore:
Mi sono trovato davanti a questa serie di messaggi

  File "sqlalchemy\engine\__init__.pyo", line 263, in create_engine
  File "sqlalchemy\engine\strategies.pyo", line 50, in create
  File "sqlalchemy\engine\url.pyo", line 116, in get_dialect
sqlalchemy.exc.ArgumentError: Could not determine dialect for 'sqlite'.

per risolvere il problema, ci sono 2 strade:
o si inserisce un import esplicito nel file Data.py (orrido),
cioè dove si fa riferimento ad sqlalchemy

from sqlalchemy.dialects.sqlite.base import dialect

o si aggiunge il percorso del modulo contenente i dialect
negli includes del file di setup di py2exe:

explicit_incl = ["sqlalchemy.dialects.sqlite.base"]

Rilanciato py2exe, ho rieseguito il file.exe e di nuovo mi viene segnalato un errore.
Controllo di cosa si tratta e trovo questo nel log:

  ...
  File "sqlalchemy\processors.pyo", line 60, in to_unicode_processor_factory
  File "codecs.pyo", line 930, in getdecoder
LookupError: unknown encoding: utf-8

In questo caso devo commetare l’opzione “ascii” del file di setup di py2exe

    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}

questo perchè la codifica “ascii” abilitata, vanifica il tentativo di utilizzo di altre codifiche (unknown encoding: utf-8)
Al terzo tentativo l’applicazione parte senza problemi.

Categorie:py2exe Tag:

Python: py2exe setup.py sample

13 Maggio 2010 Commenti chiusi

Ecco il sample che uso per creare eseguibili con py2exe.

Caratteristiche:
– unico file
– compressione attiva
– icona incorporata

Ho Utilizzato wx per la GUI del fileBrowser (che cerca il
file python sorgente) e la TextEntry per il nome
del file .exe di destinazione.

La dir di destinazione è la solita:
..\dist\

Ecco il sourcecode:

#!/usr/bin/python
"""py2exe custom setup Sample
author: bancaldo"""

import py2exe, sys, wx, os, glob
from distutils.core import setup

if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

class FileBrowser(wx.FileDialog):
    '''Class for file browser'''
    def __init__(self):
        self.fin = None
        wildcard = "File di testo (*.py)|*.py|" \
            "Tutti i files (*.*)|*.*"
        wx.FileDialog.__init__(self, None, "scegli il file", os.getcwd(),
                               "", wildcard, wx.OPEN | wx.CHANGE_DIR)
        if self.ShowModal() == wx.ID_OK:  
            print(self.GetPath())
            self.file = self.GetPath()
            self.fin = open(self.file, 'r')
        else:
            print "operazione apertura annullata"
            self.Destroy()
        self.Destroy()

class Target(object):
    '''Terget'''
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # info di versione
        self.version = "1.0.0"
        self.company_name = "Bancaldo TM"
        self.copyright = "no copyright"
        self.name = "py2exe sample files"


def main():
    '''py2exe setup starter'''
    app = wx.PySimpleApp()
    app.MainLoop()

    manifest_template = '''
    <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
    <assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
        <security>
          <requestedPrivileges>
            <requestedExecutionLevel level='asInvoker' uiAccess='false' />
          </requestedPrivileges>
        </security>
      </trustInfo>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity 
    	 type='win32' 
    	 name='Microsoft.VC90.CRT' 
    	 version='9.0.21022.8' 
    	 processorArchitecture='*' 
    	 publicKeyToken='1fc8b3b9a1e18e3b' />
        </dependentAssembly>
      </dependency>
      <dependency>
        <dependentAssembly>
          <assemblyIdentity
             type="win32"
             name="Microsoft.Windows.Common-Controls"
             version="6.0.0.0"
             processorArchitecture="*"
             publicKeyToken="6595b64144ccf1df"
             language="*" />
        </dependentAssembly>
      </dependency>
    </assembly>
    '''
    file_to_freeze = FileBrowser().file

    textentry = wx.TextEntryDialog(None, "nome file EXE?", '', '')
    if textentry.ShowModal() == wx.ID_OK:
        destname = textentry.GetValue()
    
    rt_manifest = 24
    
    explicit_incl = ["sqlalchemy.dialects.sqlite.base"]
    other_res = [(rt_manifest, 1, manifest_template % dict(prog = "Rubrica"))]

    setup_opts = {"py2exe": {"includes": explicit_incl,
                             "compressed": 1,
                             "optimize": 2,
                             #"ascii": 1,
                             "bundle_files": 1,}}
    
    test_wx = Target(description = "A GUI app",
                     script = file_to_freeze,
                     other_resources = other_res,
                     icon_resources = [(1, "images\\py.ico")],
                     dest_base = destname)

    # images    
    path = (os.getcwd() + "\\images\\")
    data_files = [('images', [png for png in glob.glob(path + '*.png')])]

    setup(data_files = data_files, # images
          options = setup_opts,
          zipfile = None,
          windows = [test_wx],
        )

if __name__ == '__main__':
    main()
Categorie:py2exe, python Tag: