Ir al contenido principal

Ralsina.Me — El sitio web de Roberto Alsina

Publicaciones sobre qt (publicaciones antiguas, página 13)

Shipping your PyQt app for windows


I ha­ve wri­tten about this in the pas­t, wi­th the ge­ne­ral con­clu­sion being "i­t's a pain in the ass".

So, no­w, he­re is how it's do­ne.

  1. Start wi­­th a wo­­­rking Py­­Qt appli­­ca­­tio­­n. In this exa­m­­ple, I wi­­ll use de­­vi­­cen­­zo­­.­­py mo­s­­tly be­­­cau­se:

    1. It is a wo­­­­­rking Py­­­Qt appli­­­ca­­­tio­­­n.

    2. It uses a big chunk of Py­­­Qt

    3. It's ea­sy to test

  2. Now you need a se­tu­p.­py. He­re's one that wo­rks, wi­th ex­ten­si­ve co­m­m­men­ts.

# We will be using py2exe to build the binaries.
# You may use other tools, but I know this one.

from distutils.core import setup
import py2exe

# Now you need to pass arguments to setup
# windows is a list of scripts that have their own UI and
# thus don't need to run in a console.

setup(windows=['devicenzo.py'],
      options={

# And now, configure py2exe by passing more options;

          'py2exe': {

# This is magic: if you don't add these, your .exe may
# or may not work on older/newer versions of windows.

              "dll_excludes": [
                  "MSVCP90.dll",
                  "MSWSOCK.dll",
                  "mswsock.dll",
                  "powrprof.dll",
                  ],

# Py2exe will not figure out that you need these on its own.
# You may need one, the other, or both.

              'includes': [
                  'sip',
                  'PyQt4.QtNetwork',
                  ],

# Optional: make one big exe with everything in it, or
# a folder with many things in it. Your choice
#             'bundle_files': 1,
          }
      },

# Qt's dynamically loaded plugins and py2exe really don't
# get along.

data_files = [
            ('phonon_backend', [
                'C:\Python27\Lib\site-packages\PyQt4\plugins\phonon_backend\phonon_ds94.dll'
                ]),
            ('imageplugins', [
            'c:\Python27\lib\site-packages\PyQt4\plugins\imageformats\qgif4.dll',
            'c:\Python27\lib\site-packages\PyQt4\plugins\imageformats\qjpeg4.dll',
            'c:\Python27\lib\site-packages\PyQt4\plugins\imageformats\qsvg4.dll',
            ]),
],

# If you choose the bundle above, you may want to use this, too.
#     zipfile=None,
)
  1. Run py­thon se­tu­p.­py py2exe and get a dist fol­der fu­ll of bi­na­ry good­ness.

And tha­t's it. Ex­cept of cour­se, tha­t's not it.

What this wi­ll do is crea­te a bi­na­ry se­t, ei­ther a fol­der fu­ll of things, or a sin­gle EXE fi­le. And tha­t's not enou­gh. You ha­ve to con­si­der at least the fo­llo­win­g:

  1. Put eve­­r­­y­­thing in re­­sou­r­­ce fi­­le­s: ima­­ges, qss fi­­le­s, ico­n­s, etc. Eve­­ry fi­­le your app nee­­d­s? Put it in a re­­sou­r­­ce fi­­le and load it from the­­re. That way you do­­n't ha­­ve to ca­­re about them if you go the "o­­­ne exe" road.

  2. Co­m­­pi­­le .ui fi­­les to .py (s­a­­me rea­­so­­n)

  3. Fi­­gu­­re out if you use Qt's plu­­gi­n­s, and make them wo­­­rk. This in­­clu­­des: using Pho­­­no­­n, using QtS­­Q­­L, and using any ima­­ge fo­r­­ma­­ts other than PN­­G.

After you ha­ve tha­t, are you do­ne? NO!

Your win­do­ws user wi­ll want an ins­ta­lle­r. I am not going to go in­to de­tail­s, but I had a good ti­me using Bi­tRo­ck's Ins­ta­ll­Buil­der for Qt. It's a ni­ce tool, and it wo­rks. Tha­t's a lot in this fiel­d.

But is that all? NO!

You ha­ve to take ca­re of the Vi­sual Stu­dio Runti­me. My su­gges­tio­n? Get a co­py of the 1.1MB vcre­dis­t_­x86.exe (not the lar­ger one, the 1.1MB one), and ei­ther te­ll peo­ple to ins­ta­ll it ma­nua­ll­y, or add it to your ins­ta­lle­r. You are le­ga­lly allo­wed (A­FAIK) to re­dis­tri­bu­te that thing as a who­le. But not wha­t's in it (un­le­ss you ha­ve a VS li­cen­se).

And we are do­ne? NO!

On­ce you run your app "ins­ta­lle­d", if it ever prin­ts an­y­thing to stde­rr, you wi­ll get ei­ther a dia­log te­lling you it di­d, or wor­se (if you are in ay­thing newer than XP), a dia­log te­lling you it can't wri­te to a log fi­le, and the app wi­ll ne­ver wo­rk agai­n.

This is be­cau­se py2exe ca­tches stde­rr and tries to save it on a lo­gfi­le. Whi­ch it tries to crea­te in the sa­me fol­der as the bi­na­r­y. Whi­ch is usua­lly not allo­wed be­cau­se of per­mis­sion­s.

So­lu­tio­n? Your app should ne­ver wri­te to stde­rr. Wri­te an ex­cep­thook and ca­tch tha­t. And then re­mo­ve stde­rr or re­pla­ce it wi­th a log fi­le, or so­me­thin­g. Just do­n't let py2exe do it, be­cau­se the way py2exe does it is bro­ken.

And is that it?

We­ll, ba­si­ca­lly ye­s. Of cour­se you should get 4 or 5 di­ffe­rent ver­sions of win­do­ws to test it on, but you are pre­tty mu­ch free to ship your app as you wis­h. Oh, mind you, do­n't upload it to do­wn­load­s.­com be­cau­se they wi­ll wrap your ins­ta­ller in a lar­ger one that ins­ta­lls bloa­twa­re and cra­p.

So, the­re you go.

En 128 líneas de código entra exactamente ESTE browser.

Por su­pues­to, po­dría ha­cer má­s, pe­ro has­ta yo ten­go mis stan­dar­d­s!

  • No usar ;

  • No usar if whate­ve­r: f()

Sal­vo eso, hi­ce al­gu­nos tru­cos su­cio­s, pe­ro, en es­te mo­men­to, es un bro­w­ser bas­tan­te com­ple­to en 127 lí­neas de có­di­go se­gún sloc­coun­t, así que ya ju­gué su­fi­cien­te y ma­ña­na ten­go tra­ba­jo que ha­ce­r.

Pe­ro an­tes, con­si­de­re­mos co­mo se im­ple­men­ta­ron al­gu­nos fea­tu­res (voy a cor­tar las lí­neas pa­ra que la pá­gi­na que­de ra­zo­na­ble­men­te an­gos­ta), y vea­mos tam­bién las ver­sio­nes "nor­ma­le­s" de lo mis­mo. La ver­sión "nor­ma­l" no es­tá pro­ba­da, avi­sen si es­tá ro­ta ;-)

Es­to noes al­go que de­ba apren­der­se. De he­cho es ca­si un tra­ta­do en co­mo no ha­cer las co­sas. Es el có­di­go me­nos pi­tó­ni­co y me­nos cla­ro que vas a ver es­ta se­ma­na.

Es cor­to, es ex­pre­si­vo, pe­ro es feo feo.

Voy a co­men­tar so­bre es­ta ver­sión.

Soporte deProxy

Un bro­w­ser no es gran co­sa si no se pue­de usar con pro­x­y. Por suer­te el sta­ck de red de Qt tie­ne buen so­por­te de pro­x­y. El chis­te es con­fi­gu­rar­lo.

De Vicenzo soporta proxies HTTP y SOCKS parseando la variable de entorno http_proxy y seteando el proxy a nivel aplicación en Qt:

 proxy_url = QtCore.QUrl(os.environ.get('http_proxy', ''))
 QtNetwork.QNetworkProxy.setApplicationProxy(QtNetwork.QNetworkProxy(\
 QtNetwork.QNetworkProxy.HttpProxy if unicode(proxy_url.scheme()).startswith('http')\
 else QtNetwork.QNetworkProxy.Socks5Proxy, proxy_url.host(),\
 proxy_url.port(), proxy_url.userName(), proxy_url.password())) if\
'http_proxy' in os.environ else None

Co­mo es la ver­sión nor­mal de esa co­sa?

if 'http_proxy' in os.environ:
    proxy_url = QtCore.QUrl(os.environ['http_proxy'])
    if unicode(proxy_url.scheme()).starstswith('http'):
        protocol = QtNetwork.QNetworkProxy.HttpProxy
    else:
        protocol = QtNetwork.QNetworkProxy.Socks5Proxy
    QtNetwork.QNetworkProxy.setApplicationProxy(
        QtNetwork.QNetworkProxy(
            protocol,
            proxy_url.host(),
            proxy_url.port(),
            proxy_url.userName(),
            proxy_url.password()))

Los abu­sos prin­ci­pa­les contra py­thon son el uso del ope­ra­dor ter­na­rio pa­ra ha­cer un if de una lí­nea (y ani­dar­lo) y el lar­go de lí­nea.

Cookies Persistentes

Es­to es ne­ce­sa­rio por­que que­rés per­ma­ne­cer lo­guea­do en los si­tios de una se­sión a otra. Pa­ra es­to, pri­me­ro tu­ve que ha­cer un pe­que­ño me­ca­nis­mo de per­sis­ten­cia, y guar­da­r/­leer los cookies de ahí.

Acá está como hice la persistencia (settings is una instancia de QSettings global):

def put(self, key, value):
    "Persist an object somewhere under a given key"
    settings.setValue(key, json.dumps(value))
    settings.sync()

def get(self, key, default=None):
    "Get the object stored under 'key' in persistent storage, or the default value"
    v = settings.value(key)
    return json.loads(unicode(v.toString())) if v.isValid() else default

No es có­di­go muy ra­ro, sal­vo por usar el ope­ra­dor ter­na­rio al fi­na­l. El uso de json me ase­gu­ra que mien­tras me­ta co­sas ra­zo­na­ble­s, voy a ob­te­ner lo mis­mo de vuel­ta, con el mis­mo ti­po, sin ne­ce­si­dad de con­ver­tir­lo o lla­mar mé­to­dos es­pe­cia­le­s.

¿Entonces, como guardo/leo los cookies? Primero se necesita acceder el "cookie jar". No encontré si hay uno global o por view, así que creé un QNetworkCookieJar en la línea 24 y la asigno a cada página en la línea 107.

# Save the cookies, in the window's closeEvent
self.put("cookiejar", [str(c.toRawForm()) for c in self.cookies.allCookies()])

# Restore the cookies, in the window's __init__
self.cookies.setAllCookies([QtNetwork.QNetworkCookie.parseCookies(c)[0]\
for c in self.get("cookiejar", [])])

Confieso mi crimen de usar comprensiones de listas cuando la herramienta correcta era un for.

Uso el mis­mo tru­co al res­tau­rar los ta­bs abier­to­s, con el mo­co agre­ga­do de usar una com­pren­sión de lis­ta y des­car­tar el re­sul­ta­do:

# get("tabs") is a list of URLs
[self.addTab(QtCore.QUrl(u)) for u in self.get("tabs", [])]

Propiedades y Señales al crear un objeto

Es­te fea­tu­re es­tá en ver­sio­nes re­cien­tes de Py­Q­t: si pa­sás nom­bres de pro­pie­da­des co­mo ar­gu­men­tos con nom­bre, se les asig­na el va­lo­r. Si pa­sás una se­ñal co­mo ar­gu­men­to con nom­bre, se co­nec­tan al va­lo­r.

Es un fea­tu­re ex­ce­len­te, que te ayu­da a crear có­di­go cla­ro, lo­cal y con­ci­so, y me en­can­ta te­ner­lo. Pe­ro si te que­rés ir a la ban­qui­na, es man­da­da a ha­ce­r.

Es­to es­tá por to­dos la­dos en De Vi­cen­zo, és­te es só­lo un ejem­plo (sí, es una so­la lí­nea):

QtWebKit.QWebView.__init__(self, loadProgress=lambda v:\
(self.pbar.show(), self.pbar.setValue(v)) if self.amCurrent() else\
None, loadFinished=self.pbar.hide, loadStarted=lambda:\
self.pbar.show() if self.amCurrent() else None, titleChanged=lambda\
t: container.tabs.setTabText(container.tabs.indexOf(self), t) or\
(container.setWindowTitle(t) if self.amCurrent() else None))

Por adon­de em­pie­zo­...

Hay expresiones lambda usadas para definir los callbacks en el lugar en vez de conectarse con una función o método "de verdad".

Hya lamb­das con el ope­ra­dor ter­na­rio:

loadStarted=lambda:\
    self.pbar.show() if self.amCurrent() else None

Hay lambdas que usan or o una tupla para engañar al intérprete y que haga más de una cosa en un solo lambda!

loadProgress=lambda v:\
(self.pbar.show(), self.pbar.setValue(v)) if self.amCurrent() else\
None

No voy ni a in­ten­tar des­en­re­dar es­to con fi­nes edu­ca­ti­vo­s, pe­ro di­ga­mos que esa lí­nea con­tie­ne co­sas que de­be­rían ser 3 mé­to­dos se­pa­ra­do­s, y de­be­ría es­tar re­par­ti­da en 6 lí­neas o ma­s.

Download Manager

Lla­mar­lo un ma­na­ger es exa­ge­rar por­que no se pue­de pa­rar una des­car­ga des­pués que em­pie­za, pe­ro bue­no, te de­ja ba­jar co­sas y se­guir bro­w­sean­do, y te da un re­por­te de pro­gre­so!

Primero, en la línea 16 creé un diccionario bars para llevar registro de los downloads.

Des­pué­s, te­nía que de­le­gar el con­te­ni­do no so­por­ta­do al mé­to­do in­di­ca­do, y eso se ha­ce en las lí­neas 108 and 109

Básicamente, con eso cada vez que hacés click en algo que WebKit no puede manejar, se llama al método fetch con el pedido de red como argumento.

def fetch(self, reply):
    destination = QtGui.QFileDialog.getSaveFileName(self, \
        "Save File", os.path.expanduser(os.path.join('~',\
            unicode(reply.url().path()).split('/')[-1])))
    if destination:
        bar = QtGui.QProgressBar(format='%p% - ' +
            os.path.basename(unicode(destination)))
        self.statusBar().addPermanentWidget(bar)
        reply.downloadProgress.connect(self.progress)
        reply.finished.connect(self.finished)
        self.bars[unicode(reply.url().toString())] = [bar, reply,\
            unicode(destination)]

No hay mu­cho golf acá sal­vo las lí­neas lar­ga­s, pe­ro una vez que me­tés en­ters es la ma­ne­ra ob­via de ha­cer­lo:

  • Pe­­dí un no­m­­bre de ar­­chi­­vo

  • Creás un pro­­­gress­­ba­­r, lo po­­­nés en el sta­­tus­­ba­­r, y lo co­­­ne­c­­tas a las se­­ña­­les de pro­­­gre­­so de la des­­ca­r­­ga.

Entonces, por supuesto, está el slot progress que actualiza la barra:

progress = lambda self, received, total:\
    self.bars[unicode(self.sender().url().toString())][0]\
    .setValue(100. * received / total)

Sí, de­fi­ní un mé­to­do co­mo lamb­da pa­ra aho­rrar una lí­nea. [fa­ce­pal­m]

Y elslot finished para cuando termina el download:

def finished(self):
    reply = self.sender()
    url = unicode(reply.url().toString())
    bar, _, fname = self.bars[url]
    redirURL = unicode(reply.attribute(QtNetwork.QNetworkRequest.\
        RedirectionTargetAttribute).toString())
    del self.bars[url]
    bar.deleteLater()
    if redirURL and redirURL != url:
        return self.fetch(redirURL, fname)
    with open(fname, 'wb') as f:
        f.write(str(reply.readAll()))

has­ta so­por­ta re­di­rec­cio­nes co­rrec­ta­men­te! Más allá d eso, na­da más es­con­de la ba­rra, guar­da los da­to­s, fin del cuen­ti­to. La lí­nea lar­ga ni si­quie­ra es mi cul­pa!

Hay un pro­ble­ma en que el ar­chi­vo en­te­ro se man­tie­ne en me­mo­ria has­ta el fin de la des­car­ga. Si te ba­jás un DV­D, te va a do­le­r.

Usar el with ahorra una línea y no pierde un file handle, comparado con las alternativas.

Impresión

De nue­vo Qt me sal­va las pa­pa­s, por­que ha­cer es­to a ma­no de­be ser di­fí­ci­l. Sin em­bar­go, re­sul­ta que el so­por­te de im­pre­sió­n... es­tá he­cho. Qt, es­pe­cial­men­te usa­do vía Py­Qt es tan com­ple­to!

self.previewer = QtGui.QPrintPreviewDialog(\
    paintRequested=self.print_)
self.do_print = QtGui.QShortcut("Ctrl+p",\
    self, activated=self.previewer.exec_)

No ne­ce­si­té na­da de gol­f. Eso es exac­ta­men­te el có­di­go que se ne­ce­si­ta, y es la ma­ne­ra re­co­men­da­da de en­gan­char "C­tr­l+­p" con la im­pre­sión de la pá­gi­na.

Otros Trucos

No hay otros tru­co­s. To­do lo que que­da es crear wi­dge­ts, co­nec­tar unas co­sas con otra­s, y dis­fru­tar la in­creí­ble ex­pe­rien­ce de pro­gra­mar Py­Q­t, don­de po­dés es­cri­bir un web bro­w­ser en­te­ro (s­al­vo el mo­to­r) en 127 lí­neas de có­di­go.

De Vicenzo: un mini browser más copado

Si no que­rés leer eso de nue­vo, la idea es ver cuán­to có­di­go fal­ta pa­ra con­ver­tir el mo­tor We­bKit de Qt en un bro­w­ser "en se­rio­".

Pa­ra ello, me pu­se una me­ta com­ple­ta­men­te ar­bi­tra­ria de 128 lí­neas de có­di­go. En es­te mo­men­to lo de­cla­ro fea­tu­re-­com­ple­te (pe­ro bu­gg­y).

Los nue­vos fea­tu­res so­n:

  • Ta­­bbed bro­­w­­sing (se pue­­de agre­­ga­­r/s­a­­car ta­bs)

  • Book­­ma­­rks (se pue­­den agre­­ga­­r/s­a­­car y ele­­gir de una lis­­ta)

Es­to es lo que ya fun­cio­na­ba:

  • Zoom in (C­­tr­­l++)

  • Zoom out (C­­tr­­l+-)

  • Re­set Zoom (C­­tr­­l+=)

  • Bus­­car (C­­tr­­l+­­F)

  • Es­­co­n­­der bús­­que­­da (Es­­c)

  • Bo­­­to­­­nes de atrá­s/a­­de­­lan­­te y re­­ca­r­­gar

  • En­­tra­­da de URL que coi­n­­ci­­de con la pá­­gi­­na + au­­to­­­co­m­­ple­­ta­­do des­­de la his­­to­­­ria + arre­­gla la URL pues­­ta a ma­no (a­­gre­­ga http://, esas co­­sas)

  • Plu­­gins (i­n­­cluí­­do fla­s­h, que hay que ba­­jar apa­r­­te ;-)

  • El tí­­tu­­lo de la ven­­ta­­na mues­­tra el tí­­tu­­lo de la pá­­gi­­na (sin pro­­­pa­­gan­­da del bro­­w­se­­r)

  • Ba­­rra de pro­­­gre­­so pa­­ra la ca­r­­ga de la pá­­gi­­na

  • Ba­­rra de es­­ta­­do que mues­­tra el des­­tino de los li­nks cuan­­do pa­sas el mou­­se

  • To­­­ma una URL en la lí­­nea de co­­­man­­do (o abre http://­­p­­y­­tho­­n.org

  • Mu­l­­ti­­pla­­ta­­fo­r­­ma (fun­­cio­­­na do­n­­de fun­­cio­­­na QtWe­­bKi­­t)

Y cuan­to có­di­go es eso? 87 LI­NEAS.

O si pre­fe­rís la ver­sión que cum­ple con la PE­P8: 115 LI­NEAS.

Me ata­jo an­tes que al­guien lo di­ga: sí, el mo­tor de ren­de­ring y el toolkit son enor­mes. Lo que es­cri­bí es el "ch­ro­me" al­re­de­dor de eso, igual que ha­cen Aro­ra, Rekon­q, Ga­leo­n, Epi­phan­y, y mu­chos otros bro­w­ser­s.

Es un ch­ro­me sim­ple y mi­ni­ma­lis­ta, pe­ro fun­cio­na bas­tan­te bien, creo yo.

Aquí es­tá el de­mo (bu­gg­y):

Mas o me­nos ha­ce lo que es­pe­ra­ba que se pue­die­ra lo­gra­r, pe­ro le fal­tan arre­glo­s.

Pa­ra ver el có­di­go, va­yan a su ho­me pa­ge: http://­de­vi­cen­zo­.­google­co­de.­com


Contents © 2000-2023 Roberto Alsina