<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andy Bulka on Medium]]></title>
        <description><![CDATA[Stories by Andy Bulka on Medium]]></description>
        <link>https://medium.com/@abulka?source=rss-4c66d4d2dfca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b_PRBuVtILUs__5K</url>
            <title>Stories by Andy Bulka on Medium</title>
            <link>https://medium.com/@abulka?source=rss-4c66d4d2dfca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:16:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abulka/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TodoMVC implemented using a game architecture — ECS.]]></title>
            <link>https://medium.com/@abulka/todomvc-implemented-using-a-game-architecture-ecs-88bb86ea5e98?source=rss-4c66d4d2dfca------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bb86ea5e98</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Andy Bulka]]></dc:creator>
            <pubDate>Mon, 18 May 2020 02:18:54 GMT</pubDate>
            <atom:updated>2020-05-21T11:35:16.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>TodoMVC implemented using a game architecture — ECS.</h3><h4>Building traditional GUIs with the Entity Component System</h4><p>Is the <a href="https://en.wikipedia.org/wiki/Entity_component_system">Entity Component System</a> any good for building traditional GUIs?</p><p>It turns out that the answer is yes! Whilst ECS is most commonly used in building games, it can also be used for building a traditional web “form” style application like TodoMVC. However you will need to radically rethink how models, their data and behaviour is organised.</p><p>This is arguably a refreshing, mind-blowing lesson in GUI programming! 🤯😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5M2IdCxdQZ6h925XxW95Jw.png" /><figcaption>The TodoMVC web app</figcaption></figure><p>Live <a href="https://abulka.github.io/todomvc-ecs/index.html">demo</a>.</p><h3>ECS — Entity Component System Architectural Pattern</h3><p>The ECS (Entity Component System) architecture is the new hotness in game developer circles. Its a way of architecting your software that rejects Models as classes in favour of a more deconstructed, data driven approach. The results, in gaming apps at least, are massive reductions in complexity and huge increases in performance and maintainability.</p><blockquote><em>When I read about ECS it got me thinking — why not use it for more traditional software, not just games?</em></blockquote><p>You can read about Entity Systems in this <a href="https://en.wikipedia.org/wiki/Entity_component_system">Wikipedia article</a>. The basic idea is to take the Object (that contains identity, data and behaviour) and ‘deconstruct it’.</p><ul><li>Entity = like a model, but <em>has no data and no behaviour</em> 🤯 Entities are lightweight and dumb — just an id or name</li><li>Component = data</li><li>System = behaviour</li></ul><h3>Example — Traditional Class vs ECS</h3><p>A traditional class Model of a Todo item would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7061e3decc124e06a4b53229dc6073ee/href">https://medium.com/media/7061e3decc124e06a4b53229dc6073ee/href</a></iframe><p>which would generate:</p><pre>$ node example.js </pre><pre>Todo item make lunch has id 1 and is completed<br>Todo item wash dishes has id 2 and is not completed</pre><p>whereas the ECS approach would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ece98fb66c8a1fc6636d646c986a17c/href">https://medium.com/media/4ece98fb66c8a1fc6636d646c986a17c/href</a></iframe><p>Let’s break this down:</p><ol><li>Creating an entity is just engine.entity()</li><li>Give the entity some data fields with entity.setComponent(&#39;data&#39;, {title, completed, id}). The name of this component happens to be &#39;data&#39; because I chose that name, but I could have named it something like &#39;todo-data&#39;</li><li>Add some behaviour with engine.system - the code inside will run <em>for each</em> entity that has the &#39;data&#39; component.</li></ol><p>Notice there is no explicit looping. The System loops for us. All entities who have the ‘data’ component will be looped through. You can add additional components to the list, which will mean the system will loop through all components who have <em>all</em> those components (an and selector).</p><p>You can have multiple systems, they will run in the order declared. Each time engine.tick() is run, all Systems will be run.</p><p>Notice there is no need to store a master list of todos - the ECS holds all entities for us. If we did want to generate a list of todos, its actually a bit tricky. See the next section <a href="https://github.com/abulka/todomvc-ecs#gathering-results-whilst-looping">Gathering results whilst looping</a>.</p><h3>The freedom to attach any Component to any Entity</h3><p>You now have the freedom to attach any Component to any Entity. But why bother?</p><p>You would think that a pure data Component like Position {x:0, y:0} is always closely tied with a specific Entity - so why break them apart? For example a Ball has a Position, a Person does not! What a Person entity surely needs instead is a Name {firstname:&#39;John&#39;, surname:&#39;Smith&#39;} etc.</p><p>Well, it turns out that the opposite is often true — entities like Ball, Bullet, Car <em>all</em> need Position. And in more business oriented applications, Person, Employee, Manager <em>all</em> need a Name.</p><p>Thinking further along these lines, another useful component might be Address - many Entities would need that. Thus having a <em>single</em> declaration of Name and Address etc. which can be re-used many times saves having duplicate declarations and associated errors.</p><h3>What about using Inheritance?</h3><p>If you think that using class <em>inheritance</em> can achieve the goal of declaring Address only once - you would be right. However most languages support only single inheritance, so good luck with forcing disparate inheritance trees to inherit from a common Address class - that&#39;s a bit awkward.</p><p>With languages that support multiple inheritance (e.g. Python), you will have more luck — in fact multiple inheritance comes closest to matching the idea of ECS, where you can arbitrarily compose a model entity from as many Component data aspects as you like.</p><h3>What about using Composition?</h3><p>You could also solve the problem through <em>composition</em> — a class could reference a common instance of Address and any other common classes it needs. This would also achieve the goal of declaring Address only once and providing &#39;mix and match&#39; composability of Models, that ECS has.</p><h3>The ECS solution to composability</h3><p>This is how we arbitrarily attach data Components to entities in ECS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ed744ec1842680e96da3a95de828c59/href">https://medium.com/media/6ed744ec1842680e96da3a95de828c59/href</a></iframe><p>We have created an entity person 1 and attached both a Name and an Address Component. Running</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7c77d412576276a3940a69d1e45913f/href">https://medium.com/media/f7c77d412576276a3940a69d1e45913f/href</a></iframe><p>results in:</p><pre>person 1 {&quot;firstname&quot;:&quot;John&quot;,&quot;surname&quot;:&quot;Smith&quot;} {&quot;number&quot;:12,&quot;street&quot;:&quot;Bounty Drive&quot;,&quot;state&quot;:&quot;WA&quot;}</pre><p>You can attach even Components that have no actual data. Sometimes this technique is useful to mark entities e.g. a dirty Component flag for rendering purposes, or a delete Component flag etc. so that a System selector matches on this condition (of having this flag) and triggers that particular System to run. This technique is further discussed in the section entitled <a href="https://github.com/abulka/todomvc-ecs#components-as-flags">Components as Flags</a>, later.</p><p>Here is an example of adding various ‘Flag’ Components to an entity — of course you would name the components better e.g. in TodoMVC-ECS editingmode is such a Component used as a flag. The presence of the flag Component on an entity will trigger a particular System. Notice that in this example the Component data is either an empty object {} or null. Typically (though your situation may be different) its the presence of the Component attached to the entity that matters, not the Component data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cc3f8e38db582b10f389fba90cbccd0/href">https://medium.com/media/0cc3f8e38db582b10f389fba90cbccd0/href</a></iframe><p>This freedom to decouple data from entities is very powerful, especially when we take the next and final step in understanding ECS — Systems.</p><h3>Systems</h3><p>Systems are where most of the application behaviour happens, including rendering/updating the DOM.</p><p>The idea is to have lots of Systems, one after each other, each doing a bit of work that can be reasoned about simply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_w4swGc0bDAy80P3VPYtOw.png" /><figcaption><em>TodoMVC-ECS Architecture — ‘Literate Code Map’ diagram</em></figcaption></figure><ul><li>The above diagram was generated semi-automatically from Javascript source code residing in GitHub using <a href="https://github.com/abulka/todomvc-ecs/blob/master/www.gituml.com">GitUML</a>.</li><li>Click <a href="https://abulka.github.io/todomvc-ecs/images/ecs-full.svg?sanitize=true">here</a> for more diagram detail as a .svg and the ability to zoom.</li><li>View this actual <a href="https://www.gituml.com/viewz/170">diagram 170</a> on GitUML.</li></ul><h3>Selecting</h3><p>Systems are code blocks which run across subsets of entities which have <em>all</em> the components listed in each System’s declaration e.g. [&#39;data&#39;, &#39;dirty&#39;] means all entities that possess both these components will be processed.</p><p>Here is an example of a two Systems, which run one after the other:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c8967f8f3f510499aef802ac8d692fd/href">https://medium.com/media/0c8967f8f3f510499aef802ac8d692fd/href</a></iframe><p>I like to think of the list of Components declared on each System as like a CSS selector, except it applies to ECS entities. The system will loop through all entities who possess all the Components listed (an and concept).</p><h3>Pipeline approach</h3><p>System blocks run in the order declared, one after the other, each time engine.tick() is called. Each System will iterate as needed, then exit and the next System will run.</p><p>Systems form a multi-stage processing pipeline. A System often builds on the work of the previous System — this is a strength of this ECS architecture, the ability to break down work into easy to understand stages.</p><p>See <a href="https://github.com/abulka/todomvc-ecs#systems-in-this-todo-app">Systems in this Todo app</a>, below, to see a table Systems I came up with to implement TodoMVC and what they do. Its suprising to discover that one can build an app in this way.</p><h3>Looping</h3><p>As you have probably noticed, looping is central to ECS. I guess it comes from the gaming heritage, where there are many game objects to process.</p><blockquote><em>If you have an explicit for loop in your code you are probably doing ECS wrong! Use a System instead.</em></blockquote><p>Systems magically iterate across entites that match certain Components e.g. all entities who have a Speed component and a Position component. Its like having a CSS selector and running a code block for all matches.</p><p>If you don’t want to loop through anything, and just have to do some miscellaneous work at any stage, simply insert a System that matches on a single component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b11581a4cf1796aa445ec12a375ed35e/href">https://medium.com/media/b11581a4cf1796aa445ec12a375ed35e/href</a></iframe><p>Read more about this technique below, in the section <a href="https://github.com/abulka/todomvc-ecs#The-housekeeping-Component-trick">The housekeeping Component trick</a></p><h3>The tick</h3><p>When there is any change to the application, you need to trigger engine.tick() again, in order to re-render the GUI. The tick function simply re-runs all Systems again.</p><p>Remember to boot your app with a lone call to engine.tick() at the bottom of the app javascript file.</p><p>Game based ECS systems typically run tick in a loop at 60fps which is not appropriate for our form based GUI, but by all means, enable the automatic looping feature of your ECS if you feel that strategically calling tick is too much to think about!</p><p>You may also have a use for the handy &#39;tick:after&#39; and &#39;tick:after&#39; events to run code before and after each tick runs all the Systems.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aca8442983105155128519859fb47e3/href">https://medium.com/media/9aca8442983105155128519859fb47e3/href</a></iframe><h3>ECS — <strong>extra useful tricks</strong></h3><p>I ended up creating a couple of tricks to get ECS to do what I wanted in certain cases.</p><h4>Gathering results whilst looping</h4><p>Generating a list of todos is pretty easy — just declare a System which matches a Component that all todo entities have, and push each entity onto a list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a90d664ca40e9bdc3651617cab444c4d/href">https://medium.com/media/a90d664ca40e9bdc3651617cab444c4d/href</a></iframe><p>You can gather anything you want in this way, e.g.</p><ul><li>push the whole data Component with push(data)</li><li>push only the todo title with push(data.title)</li><li>push the entity itself with push(entity)</li><li>etc.</li></ul><p>The only problem is that next time you tick(), todos is not cleared and your list will double, triple, quadriple etc. The easiest way to solve this is to utilise the &#39;tick:before&#39; event and clear todos before each tick run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba2fd5293786624a37fb55fad6cbf681/href">https://medium.com/media/ba2fd5293786624a37fb55fad6cbf681/href</a></iframe><p>I use the above technique to generate the JSON of all the todo data to persist in the browser storage. Try the <a href="https://abulka.github.io/todomvc-ecs/index.html">live demo</a> and hit refresh — the same todo items survive, because of this persistence.</p><h4>Advanced reset of a variable</h4><p>If you want to reset some variables or do some processing in the middle of the pipeline e.g.</p><pre>System1<br>System2<br>        &lt;-- reset a variable here<br>System3</pre><p>then you will need to create a System whose codeblock runs once, and define it at the appropriate point in your code — after System2 and before System3.</p><p>To create a System whose codeblock runs once, use <a href="https://github.com/abulka/todomvc-ecs#The-housekeeping-Component-trick">The housekeeping Component trick</a>, below, which defines a special Component and Entity pair, then create a System matching on them.</p><h4>The housekeeping Component trick</h4><p>If you need to initialise variables in the middle of a system run (remember the order that systems run in is critical, with one system often feeding results into another system) then reseting at the start or beginning of a tick won’t work. We need to be able to define a System which does the reset or housekeeping tasks, which we can place anywhere in our list of Systems. And we don’t want that System to loop, we want it to run once. Which means it must match only one entity.</p><p>The solution is to define a special Component and Entity pair</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/283466cedd31fa010bac1599be1ccc3b/href">https://medium.com/media/283466cedd31fa010bac1599be1ccc3b/href</a></iframe><p>then whever you need to run some code, insert a System like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c040772689a67db4706a9cb77061564/href">https://medium.com/media/8c040772689a67db4706a9cb77061564/href</a></iframe><p>The entity name &#39;single-step&#39; is arbitrary and can be anything. The Component name &#39;housekeeping&#39; is also arbitrary, but is referred to in Systems, as you can see in the above example.</p><p>You can use this technique to insert as many sytems like this as you like, at the appropriate places in your code. I’m not sure if it is kosher ECS usage, but its a technique I found I needed.</p><h3>Full code for gathering a list of todos</h3><p>Thus the full code for gathering a list of todos, using the above housekeeping system technique, is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fab293795c19283fb7bc22d100b2652f/href">https://medium.com/media/fab293795c19283fb7bc22d100b2652f/href</a></iframe><h3>Components as Flags</h3><p>Systems ‘doing stuff’ typically means updating component or other data and rendering based on component data. Interestingly, it can even mean <em>adding and removing components from entities</em>, which may cause other Systems to run, which hadn’t previously been running because entities with the right combination of components that the Systems were looking for did not exist.</p><p>For example, my &#39;think-todoitem&#39; System decides whether a todo entity needs the GUI DOM &lt;li&gt; created or updated, adding either the component &#39;insert&#39; or &#39;update&#39; to each entity. <em>Note that the &#39;insert&#39; and &#39;update&#39; components have empty data </em><em>{} attached thus the component acts like a flag</em>.</p><p>I use this trick extensively in this Todo implementation.</p><p>When I asked an ECS expert about this approach, he said:</p><blockquote><em>Attaching and detaching components in order to activate a system is absolutely the way to go. In fact, it is one of the biggest advantages of using ECS, since, in this way, you are changing the behaviour by taking advantage of the composition.</em></blockquote><h3>Encapsulating Systems into classes</h3><p>Just because we are deconstructing classes into an ECS approach doesn’t mean we can’t use classes to help us. Systems still work when created inside classes — they are registered with the engine and will run ok.</p><p>You might want to use a class to group variables that are private to specific Systems together, so they do not pollute the outer namespaces e.g. this.todos_data in the example below. Classes are also handy places to define functions that are private to specific Systems, too e.g. the save() method in the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d7500b00fcf4f4b19c4ccbca0766c1/href">https://medium.com/media/63d7500b00fcf4f4b19c4ccbca0766c1/href</a></iframe><p>This use of Systems inside Classes is arguably nicer and more encapsulated.</p><p>The only thing to watch out for is that you need to instantiate the classes in the correct order, so that their Systems are created (via their constructors) at the appropriate point in the ‘pipeline’ of Systems.</p><h3>Other thoughts on ECS</h3><h3>No Events needed</h3><p>Whilst there are GUI events from the DOM, notice that there are no ‘internal’ events in this implementation. This is a very real benefit, as event flow can be hard to follow.</p><p>The efficiency of the ECS approach is not as good as an event based approach however, because we are re-rendering more than we need to. Internal events give us a finer grained control over what needs to be updated in the GUI. See my <a href="https://github.com/abulka/todomvc-oo%22">TodoMVC-OO</a> implementation to see how efficiently event notifications from the model to controllers can work.</p><h3>Optimising GUI updates</h3><p>Adding a dirty flag to entities that need updating can fix this brute force re-rendering inefficiency. I’d recommend a Component called &#39;dirty&#39; which can be attached to entities. Then refine your Systems to only match on todo data that is dirty e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f334eb4c5855825cd47e497d3711700c/href">https://medium.com/media/f334eb4c5855825cd47e497d3711700c/href</a></iframe><p>Notice that the last line of this System <em>removes</em> the dirty flag/component. When you change the data of the entity, you would add the &#39;dirty&#39; component e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/678158ece1a2c1957ddd52f9d8cde946/href">https://medium.com/media/678158ece1a2c1957ddd52f9d8cde946/href</a></iframe><h3>Systems in this Todo app</h3><p>Systems are where most of the behaviour lives. The idea is that each System is a loop which ‘queries’ our little database of entities and components and does something with the matching entities and components. I came up with the following Systems, which run in the following order, top to bottom, pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNcOFQUArUTZEHzuhtjmVQ.png" /><figcaption>Systems in the TodoMVC-ECS app</figcaption></figure><p>View the <a href="https://github.com/abulka/todomvc-ecs">TodoMVC-ECS GitHub project</a> for a text version of the above table.</p><p>That’s a lot of Systems! But each System runs after the other, and each one is easy to reason about. That’s the benefit of ECS — its more ‘flat’ I suppose.</p><p>Remember, the systems will only run when you call engine.tick(), so don&#39;t forget to do that. When you want all the Systems to run again, simply call engine.tick() again.</p><h3>Choosing an ECS framework</h3><p>Entity Component System frameworks are actually relatively simple. They offer ways of:</p><ol><li>defining Entities,</li><li>adding Components (data objects) to those entity instances,</li><li>defining Systems - which are code blocks which run across subsets of matched Components.</li><li>a tick function</li></ol><p>For this project I chose to use the javascript <a href="https://www.npmjs.com/package/jecs">Jecs</a> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*0EFDqSB_5kVM-S8bgx5bVQ.png" /><figcaption><em>Jecs ESC Framework for Javascript — UML diagram</em></figcaption></figure><ul><li>The above diagram was generated semi-automatically from Javascript source code residing in GitHub using <a href="https://github.com/abulka/todomvc-ecs/blob/master/www.gituml.com">GitUML</a>.</li><li>Click <a href="https://abulka.github.io/todomvc-ecs/images/jecs.svg?sanitize=true">here</a> for more diagram detail as a .svg and the ability to zoom.</li><li>View this actual <a href="https://www.gituml.com/viewz/168">diagram 168</a> on GitUML.</li></ul><p>The single file jecs.js can be copied into your project and with the usual &lt;script src=&quot;jecs.js&quot;&gt;&lt;/script&gt; you are all set to go. Or you can npm install jecs and require it in your node projects.</p><p>For my Python ECS projects I use <a href="https://github.com/benmoran56/esper">Esper</a> which is a lightweight Entity System for Python, with a focus on performance.</p><h3>Conclusion</h3><p>This approach to wiring up GUI’s has been most refreshing. I find the ECS approach fascinating and will be looking for ways to use decoupled Systems in my future projects.</p><h3>Resources</h3><h4>Demo</h4><ul><li>Running demo <a href="https://abulka.github.io/todomvc-ecs/index.html">here</a>, fully implements the TodoMVC specification.</li><li>Study the final code in this repository, specifically <a href="https://github.com/abulka/todomvc-ecs/blob/master/js/app.js">app.js</a>.</li></ul><h4>ECS</h4><ul><li>The <a href="https://github.com/abulka/todomvc-ecs">TodoMVC-ECS GitHub project</a> for this article.</li><li><a href="https://www.npmjs.com/package/jecs">Jecs</a> ECS library used in this project. There are others like <a href="https://www.npmjs.com/package/gg-entities">GGEntities</a> etc.</li><li><a href="https://abulka.github.io/gui-showdown/main_ecs.html">GUI Showdown ECS</a> another example of an app implemented using the ECS architecture (Javascript, open source). Aso see <a href="https://github.com/abulka/gui-showdown">GUI Showdown ECS in Python</a>.</li></ul><h4>TodoMVC related</h4><ul><li><a href="https://github.com/abulka/todomvc-oo">TodoMVC-OO</a> GitHub Repo — another of my TodoMVC implementations. The classic Javascript TodoMVC app implemented without a framework, using plain Object Oriented programming.</li><li>Official <a href="http://todomvc.com/">TodoMVC project</a> with other TodoMVC implementations (e.g. Vue, Angular, React etc.)</li></ul><h4>Diagramming</h4><ul><li><a href="https://www.gituml.com/">GitUML</a> diagramming used for this project</li><li><a href="https://github.com/abulka/lcodemaps">Literate Code Mapping</a> diagramming used for this project</li></ul><h3>Credit</h3><p>Created by <a href="http://andypatterns.com/">Andy Bulka</a></p><p>Note: This project is not not officially part of the <a href="http://todomvc.com/">TodoMVC project</a> — as it does it meet the criterion of “having a community” around it.</p><h4>Other Links:</h4><ul><li><a href="http://www.gituml.com/">GitUML</a> my biggest Javascript (and Python) project to date, with a complex GUI, which I am refactoring using the techniques in this article. GitUML lets you visualise your Github source code as UML via point and click, and have UML diagrams update automatically as you check in code.</li><li><a href="http://www.andypatterns.com/">More about me</a>, my MVC design patterns and other articles.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bb86ea5e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TodoMVC implemented using traditional OO, Controllers and Events.]]></title>
            <link>https://medium.com/@abulka/todomvc-implemented-using-traditional-oo-controllers-and-events-5e4c09f80cd4?source=rss-4c66d4d2dfca------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4c09f80cd4</guid>
            <category><![CDATA[todomvc]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Andy Bulka]]></dc:creator>
            <pubDate>Mon, 18 May 2020 02:15:02 GMT</pubDate>
            <atom:updated>2020-05-18T02:15:02.163Z</atom:updated>
            <content:encoded><![CDATA[<h4>TodoMVC implemented in a classic Object Oriented way</h4><p>The classic Javascript <a href="https://github.com/tastejs/todomvc">TodoMVC app</a> implemented without a framework, using plain Object Oriented programming + a traditional MVC design pattern. Distinct, mediating Controller objects are the key to this implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5M2IdCxdQZ6h925XxW95Jw.png" /><figcaption>The TodoMVC web app</figcaption></figure><p>Running demo <a href="https://abulka.github.io/todomvc-oo/index.html">here</a>.</p><h3>MVCA Architectural Pattern</h3><p>This project fully implements the TodoMVC specification. It is implemented without a framework, using plain Object Oriented programming + the MVCA architectural design pattern:</p><p>Whilst the MVC (Model View Controller) pattern is commonly and glowingly referred to, implementations can vary widely. Most documentation on MVC, including the official <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">wikipedia article</a> is vague on definitions and details. This TodoMVC-OO project uses the MVCA pattern (formerly the <a href="https://github.com/abulka/todomvc-oo/blob/master/docs_root/mgm.md">MGM</a> pattern) which is a clear and unambiguous interpretation of MVC, with the following key ideas:</p><ul><li>The <strong>View</strong> means a modern GUI framework, and therefore is usually already available to be used by the programmer.</li><li>One or more <strong>Controllers</strong> mediate between the View and the rest of the Application, listening for GUI events. Nobody else knows about the View.</li><li>The <strong>Model</strong> is traditional data, may contain some business logic, and may broadcast events when its attributes change.</li><li>The <strong>Application</strong> owns the model(s), holds view state and contains some business logic methods.</li><li>An <strong>Eventing</strong> system is needed, traditionally Observer pattern but the stronger decoupling and the proper event objects of the Publisher-Subscriber pattern is preferred.</li></ul><p>Thus MVCA simply means “Model View Controller Application” — all four roles are necessary to any implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*EWkPBNGiMpR4RQ_CX-jYbw.png" /><figcaption>TodoMVC-OO uses the MVCA Architecture — image generated by <a href="http://www.gituml.com/">GitUML</a></figcaption></figure><p><em>The above diagram was generated semi-automatically from Javascript source code residing in GitHub using </em><a href="http://www.gituml.com/"><em>GitUML</em></a><em>.</em></p><p><em>Click </em><a href="https://abulka.github.io/todomvc-oo/images/mvca-architecture-v2.svg?sanitize=true"><em>here</em></a><em> for more diagram detail as a .svg and the ability to zoom.</em></p><p><em>View this actual </em><a href="https://www.gituml.com/viewz/181"><em>diagram #181</em></a><em> on GitUML.</em></p><h3>MVCA In Detail</h3><p>Let’s go through the four parts of the MVCA pattern, which is precisely adhered to by this TodoMVC-OO implementation. Actually there is a fifth important part — the eventing system — which glues it all together —let’s look at the Model first.</p><h3>Model</h3><p>The Model is traditional, may contain some business logic, and may broadcast events when its attributes change.</p><p>By traditional, I mean the Model does not know about anything else except perhaps other models. Its the core model of your data, the domain of the what the application is all about. In the case of the Todo application, it is a collection of Todo items, which can be marked completed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/643c1fd30aa0386b53f9acfa91b730a2/href">https://medium.com/media/643c1fd30aa0386b53f9acfa91b730a2/href</a></iframe><p>The Model is usually broken into many smaller interconnected models in an attempt to reflect the real world domain being implemented as software. The Model can be implemented as mere objects in memory or a full-fledged database model, or a <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> mapping between the two. In our case, we have a pure memory model, which gets persisted into local browser storage as JSON.</p><p>You will find that some ‘model’ concepts are more about how the information is presented in the GUI, thus I recommend these are kept as attributes of the Application class, and referred to as the <em>view state</em> or <em>view model</em>. The attribute filter is an example of such view state. The Application class can also hold collections of models which is what we do in this project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd8324683bd20390930e6c6a1f478ed9/href">https://medium.com/media/fd8324683bd20390930e6c6a1f478ed9/href</a></iframe><p>The model can be fat or thin — a fat model will have more business logic in the model. A thin model will most business or application logic in the Application class, treating the model as just data structures.</p><p>Finally, the Model needs to participate in the internal eventing system. Whenever an attribute changes it should send out a notification event — this is why most attributes of our TodoItem class are accessed via getter and setter methods. For example setting title or completed will trigger an internal event to whoever may be listening. This internal eventing mechanism is how Controllers know to update the GUI with updated model information.</p><h3>View</h3><p>The View means a modern GUI framework, and as such is already available to be used by the programmer. In our case, our modern GUI framework is the browser DOM which you can build in HTML:</p><pre>&lt;input id=&quot;toggle-all&quot; class=&quot;toggle-all&quot; type=&quot;checkbox&quot;&gt;</pre><p>then Controllers use the GUI native eventing system to listen for interesting events</p><pre>this.gui.$toggle_all.on(&#39;change&#39;, handler)</pre><h3>Controller</h3><p>The Controller is the most interesting aspect of MVC.</p><p>In many software designs, the Controller isn’t necessarily a single thing. A bunch of stray GUI event handler functions are in reality, part of the ‘controller role’. Code that copies data from the model into the GUI/DOM is also part of the Controller role. I feel the challenge of GUI architectures is to tame the role of Controller into some semblance of coherance and symmetric organisation. Which is why MVCA prescribes creating Controller classes.</p><p>In TodoMVC-OO we have a Controller class ControllerTodoItem and instantiate one per TodoItem model instance. That&#39;s arguably a lot of controller instances, but this approach allows fine grained updating of the DOM. In contrast, the Jquery version of TodoMVC rebuilds the entire todo DOM on each refresh - something that might become inefficient for non-toy apps.</p><p>In TodoMVC-OO we have a Controller class ControllerHeader for looking after the header part of the GUI and ControllerFooter for looking after the footer area, which is where the filter buttons are and the count of uncompleted todo items is displayed. The number of Controllers you create is up to you: one Controller per GUI element for fine grained updates, a more relaxed approach of one Controller per related group of GUI elements (my preference) or arguably even one Controller for all GUI elements! I go into more academic detail on this topic in my <a href="https://github.com/abulka/todomvc-oo/blob/master/docs_root/mgm.md">MGM</a> pattern paper.</p><p>By clearly defining what a mediating Controller is, and organising our app into different sensible controllers, we tame our design and prevent it from turning into spaghetti.</p><ul><li>View events <em>only</em> talk to Controllers:</li><li>View events (‘gui events’ e.g. via .on(&#39;click&#39;, ...)) go to one or more Controllers.</li><li>Controllers update the View, usually in reponse to an ‘internal event’ notification.</li><li>The Controller talks to the rest of the system:</li><li>Accesses App view state.</li><li>Calls App business logic methods.</li><li>Modifies the Model directly.</li><li>The Controller listens for ‘internal events’ broadcast from Model &amp; App.</li></ul><p>Whilst that may seem like a lot to understand, its basically saying Controllers talk to the GUI — nobody else does. Controllers then call into the rest of the system to get things done</p><p>Importantly, we must resist putting business logic into the Controller, simply let the controller call the Application to do what needs to be done. The Controller should do the minimal possible work, mediating and translating between the View and the rest of the system (the App + Model).</p><h3>Application</h3><p>The role of the Application is also important and often overlooked/undocumented. The Application owns the Model, and looks after persisting it. The Application can listen for internal Model events.</p><p>Whilst it is fine to wire Controllers directly to model instances, you will also need the Application to hold “view state” e.g. like the state of the active “filter” in this Todo application. The Application is a centralised class, a kind of hub — to hold higher level business logic and more complex model manipulations. The Application class’s functionality can of course be composed of smaller pieces as software grows more complex but a class called Application should always still exist.</p><h3>Eventing System</h3><p>Eventing is an important consideration in decoupling models from controllers, and to facilitate abstract communication between objects.</p><p>Two eventing systems should be distinguished:</p><ul><li>GUI native: The native eventing system of the GUI Framework e.g. DOM .on(&#39;click&#39;, ...</li><li>Internal: Your choice of an application system wide eventing system e.g. Publish-Subscribe e.g. document.addEventListener(&quot;hello&quot;, (event) =&gt; { ... })</li></ul><p>Both eventing systems are used in the TodoMVC-OO implementation. As you can see in the diagram above, DOM eventing reaches the Controllers, but no further. The remaining eventing is internal.</p><p>Here is a <a href="https://github.com/abulka/lcodemaps">Literate Code Map</a> of the event flow of TodoMVC-OO. Events are reified as coloured objects, each different event gets a different colour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5MNmgdXXndeTK9e7pB5uw.png" /><figcaption>TodoMVC-OO event flow.</figcaption></figure><p><em>The above diagram was generated automatically from Javascript source code residing in GitHub using </em><a href="http://www.gituml.com/"><em>GitUML</em></a><em>.</em></p><p><em>Click </em><a href="https://abulka.github.io/todomvc-oo/images/todomvc-oo-event-flow-gituml-134.svg"><em>here</em></a><em> for more diagram detail as a .svg and the ability to zoom.</em></p><p><em>View this actual </em><a href="https://www.gituml.com/viewz/134"><em>diagram #134</em></a><em> on GitUML.</em></p><p>The eventing pattern depicted here is <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">Publisher-Subscriber</a> where real event objects are ‘broadcast’ into the ether/event bus/system/whatever — allowing any code in the system to subscribe and respond — the point is, the code emitting the event does not have references to receiver object/methods.</p><p>The Javascript built in Publisher-Subscriber eventing approach is more flexible and powerful than the <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer</a> pattern since the Observer pattern <em>requires observers to know about</em> and subscribe to Subject objects, which is not always possible or convenient. More dicussion on the differences can be found <a href="https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c">in this article</a> and on <a href="https://stackoverflow.com/questions/6439512/difference-between-observer-pattern-and-event-driven-approach">Stackoverflow</a>. Thus we use Publisher-Subscriber eventing (event name → object method) rather than the traditional Observer pattern (object → object) approach.</p><p>I used to be a fan of the traditional Observer pattern but in my later years find the Publisher-Subscriber pattern to be simpler and more powerful — plus Publisher-Subscriber is built into Javascript you simply document.addEventListener(&quot;hello&quot;, (event) =&gt; { ... }) to listen and document.dispatchEvent(new CustomEvent(event_name, { detail: {from: from, data: data } })) to notify all.</p><p>The Javascript built in Publisher-Subscriber eventing system is used as the internal eventing system of this TodoMVC-OO implementation.</p><h3>Application Bootstrapping</h3><p>To get things running, some bootstrapping code will create an instance of the Application which in turn creates all the Controllers and loads the Model. The bootstrapping in TodoMVC-OO is done in app.js which creates an instance of Application which is defined in application.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be36b4b0650e23991fb54119d9903c5a/href">https://medium.com/media/be36b4b0650e23991fb54119d9903c5a/href</a></iframe><p>Notice that a config object with a list of callback methods is passed into the Application.</p><p>Giving the Application class knowledge of individual Controller classes and all the GUI view elements they need is arguably contaminating the Application class with too much GUI view and Controller knowledge.</p><p>The solution I use is to pass the Application a config object which contains a bunch of callbacks. Each callback function will magically create a Controller instance, wired to look after its GUI elements. Each callback function hides, within itself, references to the DOM - which we don&#39;t want the Application to have. In this way, the bootstrapping code and the Controller code are the only parts of the architecture that know about the View specifics (which we want to restrict).</p><p>Thus whenever the Application needs to instantiate a Controller (e.g. each time a TodoItem is created) it calls a config callback function. Another example is during bootup - some permanent Controllers need to be created, like the Controller looking after the header area, so the Application calls this.callback_config.cb_header(this) which creates an instance of the ControllerHeader wired to $(&#39;.new-todo&#39;) and $(&#39;.toggle-all&#39;). The Application only needs to know the callback function names and thus remains pure.</p><p>Notice in the config object below that each callback refers to the view through JQuery syntax e.g. $(&#39;ul.todo-list&#39;) and passes these references into the contructor of the Controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44d33aa6d60c9bccc2665165365358a8/href">https://medium.com/media/44d33aa6d60c9bccc2665165365358a8/href</a></iframe><p>Of course the Controller itself will have further references to View DOM elements, however these references should be based on searching <em>within</em> the outer DOM element passed to the Controller — thus achieving some degree of ‘component-isation’ and re-use. For example the same Controller could be used to look after different DOM elements with different element id’s.</p><h3>TodoMVC-OO <strong>Conclusion</strong></h3><p>This project fully implements the TodoMVC specification and is implemented without a framework, using plain Object Oriented programming + MVCA architectural design pattern, as described above.</p><p>Running demo <a href="https://abulka.github.io/todomvc-oo/index.html">here</a>.</p><h3>Improvements</h3><p>In this implementation, I notice that footer renders too early rather than right at the end of the initial render. Its just a subtle flash of the footer when the page is initially redrawn, but I’d like to correct this.</p><h3>Resources</h3><ul><li>Official <a href="http://todomvc.com/">TodoMVC project</a> with other TodoMVC implementations (e.g. Vue, Angular, React etc.)</li><li><a href="https://github.com/abulka/todomvc-ecs">TodoMVC-ECS</a> — My “Entity Component System” implementation of TodoMVC</li><li><a href="https://abulka.github.io/gui-showdown/main_mvca.html">GUI Showdown MVCA</a> another example of an app implemented using the MVCA architecture (Javascript, open source)</li><li><a href="https://github.com/abulka/todomvc-oo/blob/master/docs_root/mgm.md">MGM</a> pattern (older version of MVCA, presented at a Patterns Conference)</li></ul><h3>Diagramming</h3><ul><li><a href="https://www.gituml.com/">GitUML</a> diagramming used for this project</li><li><a href="https://github.com/abulka/lcodemaps">Literate Code Mapping</a> diagramming used for this project</li></ul><h3>Credit</h3><p>Created by <a href="http://andypatterns.com/">Andy Bulka</a></p><p>Note: This project is not not officially part of the <a href="http://todomvc.com/">TodoMVC project</a> — as it is does not use a MVC framework library, nor does it meet the criterion of “having a community” around it. On the other hand, perhaps a pattern is equivalent enough to a framework — after all there is a plain Javascript TodoMVC implementation officially available using ad-hoc techniques. Plus, there has been a “community” around the Object Oriented MVC pattern for decades now — hasn’t there? 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4c09f80cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django View logging is back-the-front]]></title>
            <link>https://medium.com/@abulka/django-view-logging-is-back-the-front-7f9701d501de?source=rss-4c66d4d2dfca------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f9701d501de</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[dokku]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[console]]></category>
            <dc:creator><![CDATA[Andy Bulka]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 04:34:25 GMT</pubDate>
            <atom:updated>2019-09-04T23:00:13.272Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever looked through your Django log files and console messages, felt something was out of order and didn’t make sense, but couldn’t quite put your finger on it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i_GmHmqE7ORsxh1x" /><figcaption>Photo by <a href="https://unsplash.com/@brucemars?utm_source=medium&amp;utm_medium=referral">bruce mars</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here is an example of what I mean. Here is some view code:</p><pre>def diagramz_list(request, template_name=&quot;list.html&quot;):<br>    log.info(<strong>&quot;diagramz_list has been called&quot;</strong>)<br>    ...<br>    return render(request, template_name, {&quot;object_list&quot;: diagrams})</pre><p>that gets routed via url(https://medium.com/r%E2%80%9D%5Elistz$%E2%80%9D,%20views.diagramz_list,%20name=%E2%80%9Dlistall%E2%80%9D).</p><p>Let’s look at the log file and console messages that get generated when you do the usual python manage.py runserver and using the browser, visit endpoint /listz:</p><pre>[2018–10–20 14:42:50] [INFO] diagramz_list has been called<br>[2018–10–20 14:42:51] [INFO] “GET /listz HTTP/1.1” 200 119585</pre><p>Can you see the problem?</p><p>Right — the hit on the endpoint /listz gets logged <em>after</em> the output of the logging statement which says “diagramz_list has been called”.</p><p>That’s counterintuitive for me when I do logfile analysis.</p><blockquote>IMO — the Django endpoint call should be logged <strong>immediately.</strong></blockquote><blockquote>Anything that happens during the execution of that request should be logged afterwards.</blockquote><p>Django logging via runserver has it arse-about. Even running in production, which doesn’t use Django’s local runserver technology, this problem still occurs (and we’ll see how to fix it, later).</p><p>Basically Django logs the endpoint “hit” at the <strong>end</strong> of the request processing view function, rather than at the beginning of it. For those of us trying to make sense of a sequence of events in the log file — this is confusing.</p><h3>The solution</h3><p>My solution is to use some “middleware code” to output a log message at the very, very start of each view function.</p><p>I found this <a href="https://djangosnippets.org/snippets/2624/">old snippet</a> and modified it to be Django 2/Python 3 compatible using <a href="https://docs.djangoproject.com/en/1.11/topics/http/middleware/#upgrading-middleware">this guide</a>, then added the magic logging code I wanted — see line 27 below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/669983595def8b75522c7bd82f4d1bdd/href">https://medium.com/media/669983595def8b75522c7bd82f4d1bdd/href</a></iframe><p>Most of the above code is about formatting a useful, pretty log message. The essential thing is that we are defining a class RequestLoggingMiddleware(MiddlewareMixin): and defining process_request and process_response methods. You can do what you want inside these methods — I choose to log.</p><p>Add the above file request-logging-middleware.py to some path in your project. Then add the following line of config to your middleware (in settings.py) like this:</p><pre>MIDDLEWARE = [<br>   ...<br>   &quot;SOMEPATH.request-logging-middleware.RequestLoggingMiddleware&quot;,<br>   ...</pre><p>For example if you choose to put request-logging-middleware.py in a package of your project called lib.extras then the entry should be “lib.extras.request-logging-middleware.RequestLoggingMiddleware”. If you choose to put the file in the root of your Django project, then the path need only be “request-logging-middleware.RequestLoggingMiddleware”.</p><p>Now, after restarting your Django server and visiting some urls of your Django project, your log output should look like:</p><pre><strong>[2018-10-21 14:48:21] [INFO] Endpoint /listz request 127.0.0.1<br></strong>[2018-10-21 14:48:21] [INFO] diagramz_list has been called<br>[2018-10-21 14:48:22] [INFO] Endpoint completed, 127.0.0.1 GET /listz 200 119585 (0.26 seconds) (39 SQL queries, 1.0 ms)<br>[21/Oct/2018 14:48:22] &quot;GET /listz HTTP/1.1&quot; 200 119585</pre><p>Notice that we can now see where the endpoint hit <em>first</em> begins.</p><p>Result!</p><h3>Production out of sequence issues too!</h3><p>I tend to host a lot of my work using Heroku, or its free little brother, <a href="https://github.com/dokku/dokku">Dokku</a>, on a Digital Ocean droplet (VM). With these deployment technologies, logging to file is disabled (forcibly, by Heroku) and all log messages go to stdout. These days I install a Datadog agent and forward these log messages to <a href="https://www.datadoghq.com/">Datadog</a> for monitoring.</p><p>It turns out that in such a deployment scenario:</p><blockquote>all Python and Django log messages go to <strong><em>stderr</em></strong></blockquote><blockquote>and all gunicorn log messages that deal with view hits and static file serving go to <em>stdout</em>.</blockquote><p>This phenomenon may cause ‘out of sequence’ log messages, too!</p><p>For example the Datadog Agent scans my docker containers in my Digital Ocean droplet (VM) and sends them to the lovely Datadog service. I think that the way the agent grabs those separate message streams, timestamps them and sends them to Datadog can result in stdout messages getting a slight priority over Django’s error messages — thus causing the gunicorn view requests to be logged first — as we want. A quirk of fate, perhaps, but at least it’s in our favour.</p><p>If we want to eliminate the stdout/stderr timing problems, <a href="https://stackoverflow.com/questions/24117481/django-loggers-correct-output-to-stdout-and-stderr">this stackoverflow post</a> and also perhaps <a href="https://stackoverflow.com/questions/21998567/logging-info-to-django-servers-stdout">this one</a> discuss how we can configure our logging so that everything goes to stdout. This would eliminate this possible area of log ordering confusion.</p><p>However when viewing the log messages from my deployed app in a dokku managed docker container <strong>via a terminal</strong>, e.g.dokku logs appnamethen interestingly, the sequence is the same as my local machine — the gunicorn view requests are <strong>logged last</strong>, and thus suffer the same out of sequence problem as the first part of this article.</p><p>Thankfully our middleware generated log messages give us the correct sequence all the time.</p><h3>Conclusion</h3><p>Use my middleware logging solution above. Then in all situations, local and production, whether its via terminal or via an agent like datadog, look at the <strong>middleware generated log messages</strong> not the gunicorn generated log messages, to follow the real time sequence.</p><p>I hope this article was useful. I rely on this solution for making sense of the log files in my web apps below.</p><h3>My Other Cool Software</h3><ul><li><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*s6MrotTO9abzbFNH.gif" /><figcaption><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app). A revolution in documentation — diagrams automatically update when you push code using git</figcaption></figure><ul><li><a href="http://pynsource.com/">Pynsource</a> — UML for Python (desktop app)</li><li><a href="https://pyrpn.atug.com/">Python to RPN</a> — Run Python 3 on vintage HP calculators (web app)</li><li><a href="https://print42.atug.com/">Print42</a> — Electron-Python app, non-invasive log file annotation tool that supports thermal printers</li></ul><h3>About Andy Bulka</h3><ul><li>Main website and blog <a href="http://www.andypatterns.com/">www.andypatterns.com</a></li><li>Medium article: <a href="https://medium.com/@abulka/electron-python-4e8c807bfa5e">Building a deployable Python-Electron App</a> — Using Electron as a GUI toolkit for Python.</li><li>Medium article: <a href="https://medium.com/@abulka/async-await-for-wxpython-c78c667e0872">Async/await for wxPython</a> — Python 3 GUI apps with asynchronous functionality.</li><li>Medium article: <a href="https://medium.com/@abulka/getting-python-and-wxpython-apps-into-the-ubuntu-app-store-ccca7ae537a3">Getting Python and wxPython apps into the Ubuntu app store</a></li><li>Github <a href="https://github.com/abulka?tab=repositories">https://github.com/abulka</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f9701d501de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Python and wxPython apps into the Ubuntu app store]]></title>
            <link>https://medium.com/@abulka/getting-python-and-wxpython-apps-into-the-ubuntu-app-store-ccca7ae537a3?source=rss-4c66d4d2dfca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccca7ae537a3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[snap]]></category>
            <category><![CDATA[wxpython]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Andy Bulka]]></dc:creator>
            <pubDate>Sat, 06 Apr 2019 00:22:47 GMT</pubDate>
            <atom:updated>2021-07-23T09:31:30.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>Have you ever dreamt of getting your own apps in the Ubuntu app store? Here’s how.</h4><p>I wanted to get my UML tool for Python, <a href="http://pynsource.com/">Pynsource</a>, into the Ubuntu/Snapcraft app store for a long time. This is the story of how I made that happen.</p><p>It certainly wasn’t easy. It took me a week of work, struggling with the concepts, documentation and various bugs in the tooling to finally get my app listed.</p><blockquote>Hopefully I can save you some time getting your Python command line app or wxPython GUI app published.</blockquote><h4>This article’s Contents</h4><ul><li>Overview</li><li>Part I — How to build a simple Python (non-GUI) snap</li><li>Part II — Build a wxPython GUI app, understanding snapcraft.yaml</li><li>Part III — Debugging snaps</li><li>Part IV — Troubleshooting and Snapcraft Bugs</li></ul><h3>Overview</h3><h4>What we are aiming for</h4><p>The aim is to get our Python app listed in the Ubuntu app store. This app can be a CLI (command line interface) non-GUI app that you use from the terminal, or a full blown GUI app.</p><p>Either way, you get you own app store page with screenshots and an install button. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrXq-uzsdKir0OONFV0N_w.png" /><figcaption>My Pynsource (UML for Python) Linux <a href="https://snapcraft.io/pynsource">app store page</a> on Snapcraft.io</figcaption></figure><p>The resulting app store page for Pynsource is <a href="http://The resulting app store page is https://snapcraft.io/pynsource">here</a>. Any such published app should also appear listed in the official <strong>Ubuntu Software</strong> program, which you launch from inside Linux. I could find my app by searching by its app name or by other relevant keywords, in this case I typed ‘UML’ and saw:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rttwuANu4FiF0MmJdDB2ag.png" /><figcaption>Pynsource now appears in the official Ubuntu app store</figcaption></figure><p>I didn’t have to get approval for my app to appear — I just created a Snapcraft developer account and pushed up my snap. Fantastic!</p><h4>The installation experience for end users</h4><p>Users view a page with juicy screenshots and descriptions, and that all important <strong>install</strong> button :-) How do they get to that page? You can give them the url to your app’s page on the <a href="https://snapcraft.io/store">Snapcraft.io</a> store. Or they can search for your app in the Snapcraft store, or in the “Ubuntu Software” app inside Linux.</p><blockquote>Clicking on the Snapcraft web page <strong>install</strong> button will launch the “Ubuntu Software” app installer inside Linux.</blockquote><p>You can also install app store apps using the command line. For example to install Pynsource you would type snap install pynsource. To list all apps installed in your Linux system, type snap list.</p><h4>Does your Application need approval?</h4><p>No! You don’t usually need to get approval to push your app to the Ubuntu app store if it has the default ‘strict’ permissions, which make it safe. If your app uses the more unrestricted ‘classic’ permissions then it <a href="https://forum.snapcraft.io/t/process-for-reviewing-classic-confinement-snaps/1460">needs to be approved</a>. The final permission mode is unrestricted ‘devmode’ which is for developer use — more information on the three snap confinement permissions <a href="https://docs.snapcraft.io/snap-confinement/6233">here</a>.</p><p>Getting your app featured in the curated lists and categories you see in the Ubuntu Software main page is a little unclear. Certainly you can set your app’s <em>category</em> on its Snapcraft.io page e.g. “Development”. Whilst this correctly affects searches on <a href="https://snapcraft.io/store">Snapcraft.io</a> it does not affect how your app is listed in the categories of the “Ubuntu Software” app inside Linux 18.04 because the latter uses the “Develop<strong>er</strong>” category —a bit of a mismatch— <a href="https://forum.snapcraft.io/t/snaps-are-not-appearing-in-there-category-on-snapcraft-io/8064">this post</a> talks about this issue.</p><h4>What’s a snap anyway?</h4><p><a href="https://snapcraft.io/">Snapcraft</a> and the snap store are Ubuntu’s new app store technologies. Snaps work on other Linux distros, too, which is exciting. There are a couple of other technologies that do the same thing e.g. Flatpack and AppImage, but I won’t be covering those.</p><blockquote>A snap is an app — its your program and all its dependencies rolled into a kind of zip file</blockquote><p>You shouldn’t need to change your source code in any way to create a .snap file. A .snap file is a compressed mini filesystem which contains your app files and all its dependencies.</p><p>The difference between the traditional Ubuntu app store app and a snap app is that snaps are more resilient and will work across releases and also across Linux distros — because they bundle all dependencies inside themselves. The price you pay is that they tend to be bigger in size than regular apps.</p><p>Snaps are distro independent because they are built and run against a common runtime, or “core”, and bundle the necessary libraries required to run everywhere. They do not run in a virtual machine. But you do need a virtual machine to build them (see later).</p><p>The ultimate goal for a developer is to build a .snap which is the file that you push up to the app store (or send people), you type snapcraft to build the snap — assuming you have created a snapcraft.yamlfile.</p><p>The overall process is:</p><ul><li>install the snapcraft tool</li><li>create a file called snapcraft.yaml and build your .snap file</li><li>reserve a name on the app store and push up your .snap file</li><li>edit your official snap page to add images and a description.</li></ul><h4>How popular are snaps?</h4><p>According to the official Canonical <a href="https://blog.ubuntu.com/2019/03/06/infographic-snapcraft-for-developers">statistics page</a> for snap usage,</p><blockquote>there are over three million snap installs per month,</blockquote><p>with over two thousand snap apps available — as of March 2019.</p><p>All the big name apps like Libre Office, Visual Studio Code, GitKraken, PyCharm, Sublime, Postman, Slack, Skype, VLC, Handbrake, Spotify, Plex, Gimp etc. have snaps. View the Canonical/Ubuntu/Linux/Snapcraft app store <a href="https://snapcraft.io/store">here</a>.</p><h4>Updating snaps</h4><p>The snapd deamon process updates apps for you, or you can explicitly run snap refresh to get the latest version of all your snaps.</p><h3>Part I — How to build a simple Python (non-GUI) snap</h3><p>This is a high level overview of building a snap.</p><p>The snap command and its update demon snapd should already live in recent versions of Ubuntu. If you are not using Ubuntu, see this installation <a href="https://docs.snapcraft.io/installing-snapd/6735">documentation</a> which covers other Linux distros and Mac. For example to list your existing snaps (Linux apps that have been installed from the app store) type snap list.</p><p>You typically build Linux snaps on a Linux machine. You can build snap apps on a Mac machine, though you can’t actually run the resulting snap apps on a Mac. A snap app is a .snap file which needs to be installed in Linux before it can be run.</p><ol><li>Install snapcraft e.g. snap install snapcraft on Linux or brew install snapcraft on Mac</li><li>Create a snapcraft.yaml file ← <em>this is the hard bit ;-)</em></li><li>Run the command snapcraft which creates a .snap file</li><li>Install your .snap file locally sudo snap install --devmode --dangerous *.snap</li><li>Run and test your snap by invoking its command name e.g. yourapp</li><li>If you are happy, reserve a name on the snap store snapcraft register yourapp</li><li>Push and publish your snap e.g. snapcraft push --release=edge *.snap</li><li>Edit your snap app’s web page with images and a descriptions. You can also provide a description inside the snapcraft.yaml file.</li><li>Let everybody know the url of your snap or alternatively, let them know the terminal command command to install your snap e.g. snap install yourapp.</li></ol><h4>General conceptual considerations</h4><p>The idea is to get your Python files into a .snap file, as well as any supporting libraries. And to specify a command to launch your program.</p><p>The command snapcraft looks at the snapcraft.yaml file and launches a VM (virtual machine) containing a clean, headless Ubuntu. The VM contains some core libraries (hence the core18 directive you put into thesnapcraft.yaml file). Packages are pulled off the internet and if necessary, built inside the VM.</p><p>A snapcraft.yaml file is like a Makefile, and consist of various sections. A part is a section in the snapcraft.yaml file that builds something. There used to be an ability to refer to <a href="https://docs.snapcraft.io/remote-reusable-parts/4233">remote parts</a> which are preconfigured parts (lists of install commands and package lists) which others have developed, but I believe this is no longer supported when you use the now recommended base: image approach, which we are going to follow in this article.</p><p>Plugins are extensions to the snapcraft.yaml file format that mean you can create or utilise ‘parts’ that do specialised things. The only plugins I have used are the python plugin, and the dump plugin (which helps you copy files into the snap). Developers can develop their own plugin (which happen to be written in Python), but this would be a rare thing to do.</p><p>There are several build related directories inside the VM used to build your snap: like project, stage, build, prime etc. The <strong>prime</strong> directory represents the final contents of the snap, and is ultimately the most important. You need to ensure everything that will be deployed ends up in the prime directory. The prime directory even has subdirectories like prime/etc, prime/lib/, prime/lib/python3.6/site-packages, prime/usr/include, prime/usr/lib, prime/var/lib/ etc.</p><p>You can shell into a VM and check the contents of these various build directories, including prime by dropping into a bash shell after a snapcraft build with the command snapcraft --shell-after or at any time with the multipass shell YOUR_VM_NAME command. If you don’t know the name of your VM, list them with multipass list.</p><p>You can run Python inside the VM when you are shelled into it, but you won’t be able to run GUI apps, because its a headless Linux install. And running your CLI app inside the VM is not quite the same as running it as a properly installed snap app because your Python paths etc. are not the same. You can hack around with PYTHONPATH prior to launching python, to mitigate this.</p><p>A snap file is built from the exact contents of the prime directory inside the virtual machine of your snapcraft project. A .snap file is actually secretly a directory — like an .app file is on Mac OS (which on Mac, you can explore using finder’s Show Package Contents).</p><blockquote>A .snap file is a just a compressed hierarchy of files, a filesystem if you will.</blockquote><p>Most commands in the snapcraft.yaml implicitly refer to the prime directory inside the VM, which, as I’ve mentioned, ends up as the root of your snap filesystem inside the resulting .snap file. You can explicitly refer to the prime directory in the VM as $SNAP — this is especially useful when constructing the launch command specification, as we shall see later.</p><p>Once your .snap file is built, it’s ready to install locally, run (to test it) and deploy (to the app store). The contents of the .snap can be listed using unsquashfs -l *.snap|less which is great for seeing what files are where. Remember, this listing will exactly match the recursive contents of the virtual machine’s prime directory. Each of your snap apps will be named differently and have their own virtual machine build process, and their own resulting final .snap.</p><h4>Python considerations</h4><p>Strangely, in my opinion, the snapcraft Python plugin assumes you have a setup.py file and that your app’s functionality is installed via distutils. The official <a href="https://snapcraft.io/first-snap/python">Snapcraft Python tutorial</a> assumes this approach. If your apps don’t use a setup.py (mine typically don’t) then you need to explicitly copy your source code into the VM prime directory using asnapcraft.yaml dump plugin command (which simply copies files). I’ll be using this technique throughout this article.</p><p>You can tell snapcraft to use your existing requirements.txt as well as install Python packages more explicitly using apt install commands inside your snapcraft.yaml. These Python site packages are pulled off the internet and built inside the virtual machine, and finally copied into the VM’s prime directory, e.g. if you have requests in requirements.txtthen /root/prime/lib/python3.6/site-packages/pip/_vendor/requests gets created and ends up in the final . snap file.</p><p>The version of Python seems to depend on the base snap image you choose, which currently is core18 which means Ubuntu 18.04 which in turn means Python 3.6. You may be able to override the Python version — see more info below.</p><p>When a snap is properly installed and run by a user, the PYTHONPATH of the Python shipped in the snap correctly contains both the $SNAP directory and the Python site packages directory. Your launch command specification in the snapcraft.yamlcan add other directories within the snap to the PYTHONPATH or PATH if you need to.</p><h3>Example — A simple Python (non GUI) app</h3><p>Here is a simple Python program that prints a few messages, lists the contents of the current directory and makes an internet GET request. It’s a CLI app not a GUI app, thus is much simpler to build, and you install and run it in the Linux terminal. Let’s get it into the app store!</p><p>Its actually ok to put your junk test apps in the app store — they have the same importance as big important apps, so you might want to prefix your app name with something like ‘test’ to help reduce the pollution of the single snapcraft namespace.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d89fedc5d36e457029d0fdf96698ed88/href">https://medium.com/media/d89fedc5d36e457029d0fdf96698ed88/href</a></iframe><p>You don’t need to change your source code in any way to create a .snap file app. Here is a snapcraft.yaml file for the above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3da73023f35b8307e4a14ec627162b62/href">https://medium.com/media/3da73023f35b8307e4a14ec627162b62/href</a></iframe><p>The list of stage-packages within the andy-py-cli part above (which is also tagged with the python plugin) are just the libraries that Python depends on. The above list should work perfectly well for Python 3.6 as of April 2019, though I had to spend a day chasing the libslang2 dependency and adding it to the list. When there is a missing package your snap won’t run, and you will have to figure out the sometimes mysterious package library name to add to the list. Usually the error message will be the major clue and together with some googling you should be able to find the name of the missing entry.</p><blockquote>I wish snap technology could utilise what PyInstaller does — and automatically find all the needed dependencies.</blockquote><p>Your requirements.txt for this example, should contain a single line: requests Your directory structure for this sample application is:</p><pre>|-- main.py<br>|-- requirements.txt<br>`-- snap<br>    `-- snapcraft.yaml</pre><p>Make sure your Python app runs OK outside of snapcraft e.g. python3 main.py then when happy, simply run snapcraft. The .snap file will be generated. If you get errors, see the bugs and troubleshooting section later in this article. View the contents of your snap (optional) with unsquashfs -l *.snap|less.</p><p>Then install and run the snap locally with</p><pre>sudo snap install --devmode --dangerous *.snap<br>andy-py-cli</pre><p>To publish you need to reserve your app store name and push to the app store. Use your Ubuntu login.</p><pre>snapcraft register andy-py-cli<br>snapcraft push --release=edge *.snap</pre><pre>Processing...|                                                                                                                                                                                                                                                                     <br>Ready to release!<br>Revision 1 of &#39;andy-py-cli&#39; created.<br>Track    Arch    Channel    Version    Revision<br>latest   amd64   stable     -          -<br>                 candidate  -          -<br>                 beta       -          -<br>                 edge       0.1        1</pre><p>Now you can view your <a href="https://snapcraft.io/snaps">app store page</a> which should now list this new app! And you can install your app on any Linux machine with snap install --edge andy-py-cli. If I had released to the stable channel, the --edge parameter would not have been needed.</p><p>Once I am happy to release to the stable channel, I don’t need to re-upload anything, I simply look at the Revision number of my app (see above output) which is 1 and say snapcraft release andy-py-cli 1 stable which marks this release as stable.</p><p>Go on, try it — I’ve really pushed this app into the app store and you should be able to install and run it:snap install andy-py-cli then andy-py-cli.</p><blockquote>What a great way to distribute apps and utilities — no worrying about Python installations, versions or requirements, just a single command to install.</blockquote><p>Github repo for this project is <a href="https://github.com/abulka/andy-py-cli">here</a>. You won’t be able to publish this app yourself because I have already reserved the name andy-py-cli so change the name of your app in your yaml file and register that name instead.</p><h3>Part II — Build a wxPython GUI app, understanding snapcraft.yaml</h3><p>Let’s look at what’s inside the yaml file, then look at building and deploying a wxPython GUI app.</p><h4>The mighty snapcraft.yaml</h4><p>This is where the effort lies. This file can get complex and throw a lot of people off. It could benefit from additional documentation, for example a definitive grammar/syntax , and a complete list of possibilities listed. Yes there are documentation pages approaching this level of detail, but no definitive grammar. I have found missing documentation entries and multiple versions of some documentation pages, which can get confusing. But fear not, I’m going to explain the essential steps here.</p><p>Your snapcraft.yaml for a wxPython app needs to contain:</p><ul><li>a name:</li><li>a version:</li><li>a base: directive</li><li>a part named after your program, which uses the plugin: python syntax</li><li>a part named copy-stuff (or whatever), which uses the plugin: dump syntax to copy in your Python source code.</li><li>a requirements: part that refers to your requirements.txt file</li><li>a python-packages: part which installs wxPython</li><li>a desktop-gtk3: part which installs all of wxPython’s dependencies — a long list which you can just copy and paste</li><li>an apps: part with a subsection named after your program which provides the main launch command and a reference to your .desktop file</li><li>a copy-desktop-icon-stuff: (or whatever), which uses the plugin: dump syntax to copy in your .desktop file and icon .png</li></ul><p>Use the following fragments as templates and then modify it as needed.</p><h4>Name your app</h4><pre>name: YOURAPPNAME<br>version: git</pre><p>Instead of using the current git commit as a version, you can also use any string you want e.g. ‘v0.1’.</p><h4>Add the base</h4><p>The base: core18 directive means you are building using an Ubuntu 18.04 VM with some core libraries already supplied. There is a way to run snapcraft without specifying this time saving option, but I’m not covering that legacy approach in this article.</p><blockquote>You will find examples on the web which don’t use the base directive, where builds assume a Ubuntu 16.04 system. That is old legacy snapcraft stuff, which works but is not recommended anymore.</blockquote><p>By default core18 means running Python 3.6.7. You can also run Python 2 — we’ll specify the python 2/3 version later.</p><pre>base: core18</pre><p>If you want another version of Python 3, you will need to add a new `part` to the yaml file — I have yet to figure out how to do that.</p><h4>Pick your Python version and source code location</h4><p>Then have your app YOURAPPNAME specify which version of Python (by which I mean legacy version 2 or the current version 3) and where the source code lives:</p><pre>YOURAPPNAME:<br><em>  </em>plugin: python<br>  python-version: python3<br>  source: ./src</pre><h4>The big trap for Python developers</h4><p>Note, the above part <strong>will not copy any source code</strong>, even though you are specifying where your source code is. Tricky huh!?</p><p>You <strong>need</strong> your source code to be shipped in the snap (sorry, no source code protection in Snaps, sadly).</p><p>The reason the ‘python plugin’ section specified above doesn’t actually copy your source code is that it assumes that you are providing a setup.py which assumes your python project is configured to leverage distutils file copying in a setup.py.</p><p>You see, Canonical suggest that the “easiest way” to use the python plugin is to configure your python project with distutils in a setup.py. I disagree, I think</p><blockquote>most developers do <strong>not</strong> usually set up their app’s functionality to be installed and run as a site package.</blockquote><p><strong>So to fix this</strong>, create an extra section (or ‘part’ in snapcraft speak), that explicitly copies (hence the use of the ‘dump’ plugin) all your source code into the snap. No need for setup.py or any other distutils shenanigans. The name copy-stuff is arbitrary, I just made it up.</p><pre>copy-stuff:<br>  plugin: dump<br>  source: ./src</pre><p>This will copy everything in the src/ directory into the $SNAP root directory, where it is needed. The files and subdirectores in src/ will end up in the $SNAP root directory. In most situations you probably simply want to specify source: .if your source code is in the root of your project.</p><p>If you want to be even more organised, you could copy your Python source code into a subdirectory under $SNAP by using the organize syntax of the dump plugin (its really a `copy` plugin) — just make sure your main launch command (specified in the snapcraft.yaml file under the apps: section, see below) targets the correct path of your Python source code’s main module e.g. main.py or whatever. Also ensure that your PYTHONPATH is set up correctly (you can set this up within the same launch command, using the environment: specification, examples of which are listed further below in this article).</p><h4>Requirements.txt</h4><p>To specify that you want to pip install from requirements.txt add this:</p><pre>requirements:<br>    - /root/project/requirements.txt</pre><p>Note that I had to add the /root/project/ prefix because that is where the requirements file ends up inside the VM filesystem during the snap build process. Tricky, huh. The project/ directory is one of the build directories, all of which live in the VM under /root (e.g. project, stage, build, prime etc), and contains the entire directory of your project, copied into the VM.</p><h4>The launch command — main entry point</h4><p>Now we need to specify the ultimate command to launch your app:</p><pre>apps:<br>    pynsource:<br>        command: desktop-launch python3 $SNAP/pynsource-gui.py<br>        plugs: [x11, unity7, pulseaudio, home, gsettings, network] </pre><p>Here I have have said that the command pynsource will run python3 on the file pynsource-gui.py — simple. The desktop launch stuff is what you need if you are running a GUI app.</p><p>The plugs keyword specifies which areas you want to have accessible to your app, e.g. networking, audio etc.</p><h4>WxPython considerations</h4><p>To install wxPython into your snap, you need to add the part below. You can’t simply add wxpython into requirements.txt, unfortunately. It’s a Linux limitation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efb789e05e177475072cd2e087feac26/href">https://medium.com/media/efb789e05e177475072cd2e087feac26/href</a></iframe><p>You must pick a wxPython tar url which matches your version of Python, and version of wxPython that you want. The choices are listed <a href="https://extras.wxpython.org/wxPython4/extras/linux/gtk3/">here</a>. Just change the url to suit.</p><p>I’ve also added wxasync as a dependency here, python-packages section, since I use it a lot with wxPython — see my article <a href="https://medium.com/@abulka/async-await-for-wxpython-c78c667e0872">Async/await for wxPython</a> also published on Medium.</p><p>I suppose I could have kept the wxasync dependency in requirements.txt but I’ve found that wxasync tends to install its own dependencies, one of which is wxPython. When installing things manually on Linux, I typically run pip3 install wxasync --no-dependencies but am not sure how to do that in a requirements.txt file. I’m aware there is the pip install --no-deps -r requirements.txt but 1) not sure I want to stop all my other pip packages from installing their dependencies and 2) doubt if there is any equivalent syntax that the snapcraft.yaml would recognise. So, to be safe, I simply moved the wxasync out of requirements.txt into the python-packages section, above. Presumably, theoretically, I could list <em>all</em> the pip package dependencies in the python-packages section instead, rather than using requirements.txt.</p><p>And to make sure you pull in all of wxPython’s dependencies (and associated gtk3 viz. Gnome GTK bits), you need to add this part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2995b27b561e83ff774ca3fd3a37cebc/href">https://medium.com/media/2995b27b561e83ff774ca3fd3a37cebc/href</a></iframe><p><strong>Update 2020:</strong> The latest versions of the snapcraft tool (certainly in 2020) support a simpler way to specify a gtk3 app — now all you need to do is add extensions: [gnome-3–28] and you <em>don’t need </em>the entire desktop-gtk3: part listed above — just delete all those lines and be happy! Incidentally 3–28 refers to the version of Gnome shipped in Ubuntu 18.04, which corresponds to the base: core18 VM we are using to build our snap.</p><p>There are other simplifications as a result of the extensions: [gnome-3–28]entry, like less things to list in plugs, no need for desktop-launch in the launch command, and no need for LD_LIBRARY_PATH being set (thanks to <a href="https://forum.snapcraft.io/t/getting-ready-for-stable/4305/16">Galgalesh</a> for pointing out these simplifications), thus my new simplified pynsource entry is now:</p><pre>apps:<br>    pynsource:<br>        command: python3 $SNAP/pynsource-gui.py<br>        extensions: [gnome-3-28]<br>        plugs: [unity7, audio-playback, home, network]</pre><blockquote>Thank goodness, because finding the exact list of gtk3 package dependencies can be a nightmare hunt.</blockquote><p>Aside: During my research, I started with <a href="https://github.com/Jenyay/snap-examples">these wxPython examples</a> which were helpful but old, Ubuntu 16 based, and did not use core18 snap technology. I finally figured out the snapcraft.yaml and created my own <a href="https://github.com/abulka/snap-examples-1/tree/v0.6">core18 based example</a> to help others, for a building minimal wxPython snap.</p><h4>GUI Desktop Icons</h4><p>There are instructions for setting up a desktop icon in <a href="https://forum.snapcraft.io/t/getting-ready-for-stable/4305/13">this documentation blog post</a>. Basically you have to create a .desktop text file and a .png for the icon and follow the steps outlined.</p><p>You will need to arrange your source code directory structure so that the snapcraft.yaml file is located in a directory snap and the .desktop and .png files are located in snap/gui. Always run the snapcraft command from the root of your project (e.g. where your README.md is).</p><pre>.<br>|-- README.md<br>|-- pynsource_0+git.8095336_amd64.snap<br>|-- requirements.txt<br>|-- snap<br>|   |-- gui<br>|   |   |-- pynsource.desktop<br>|   |   `-- pynsource.png<br>|   `-- snapcraft.yaml<br>`-- src</pre><p>My pynsource.desktop file is:</p><pre>[Desktop Entry]<br>Name=Pynsource<br>GenericName=UML application<br>Comment=Pynsource UML reverse engineer Python source into diagrams<br>Exec=pynsource<br>Icon=${SNAP}/meta/gui/pynsource.png<br>Terminal=false<br>Type=Application<br>Categories=Development;<br>StartupNotify=true</pre><p>Notice the reference to Icon=${SNAP}/meta/gui/pynsource.png in pynsource.desktop.</p><p>The way the files in your snap/gui/ folder: pynsource.png and pynsource.desktop get into the /root/prime/meta/gui/ directory is done magically for you by snapcraft, assuming you have followed the steps in <a href="https://forum.snapcraft.io/t/getting-ready-for-stable/4305/13">this documentation blog post</a>. Do not have a desktop: entry explicitly referring to your .desktop file — otherwise those files will not be copied.</p><p>Notice also the reference to Exec=pynsource in pynsource.desktop. This is the desktop icon launch command, which simply refers to your app name in you snapcraft.yaml.</p><h4>The final GUI snapcraft.yaml</h4><p>Here is the final <a href="https://github.com/abulka/pynsource/blob/master/snap/snapcraft.yaml">snapcraft.yaml</a> that we have been constructing above, for <a href="http://pynsource.com/">Pynsource</a>, which has been updated in 2020 to use the simplified magic of the extensions: [gnome-3–28]entry:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f8b763297a29aed3326227329e11b8/href">https://medium.com/media/b7f8b763297a29aed3326227329e11b8/href</a></iframe><p>For comparison, here is another example <a href="https://github.com/abulka/pynsource/blob/master/Research/async%20play/snapcraft.yaml">snapcraft.yaml</a> for a simpler, one file wxPython app called rubber-band-async (which you can install in Linux via the snap store <a href="https://snapcraft.io/rubber-band-async">here</a>).</p><h4>Building the GUI based snap</h4><p>Once you have your snapcraft.yaml just run snapcraft and wait for the .snap file to be built. This will take some time.</p><p>You may occasionally need to run snapcraft clean to clear out old build attempts. Unfortunately partial cleans via the snapcraft clean -s flag are currently not implemented for a core18 based build, which is the recommended way to use snapcraft. On my VM on a powerful iMac I was faced with one hour builds, because after a snapcraft clean the Ubuntu virtual machine needs to be re-downloaded again, and everything built from scratch. Your mileage may vary re build times. <strong>Update 2021</strong>: You can actually <a href="https://forum.snapcraft.io/t/what-did-snapcraft-clean-s-do/19764">clear out a specific part</a> if it is causing problems, by specifying the part name, which is much faster than a wholesale snapcraft clean— simply run e.g. snapcraft clean copy-stuff to clear out the cached part ‘copy-stuff’.</p><p>Once built, install the snap locally with sudo snap install --devmode --dangerous *.snap then run it with name of the command e.g. pynsource.</p><p>For a GUI app, you will see warnings about Gtk-Message: Failed to load module “canberra-gtk-module” — just ignore these, apparently everyone gets these and they can be ignored. Nobody knows how to get rid of them. For a GUI app, users won’t see any such messages anyway.</p><h4>Publishing the GUI snap</h4><p>When pushing you can of course specify the exact name of the snap, rather than using *.snap.</p><pre>snapcraft login <em>(use ubuntu one auth)<br></em>snapcraft register YOURAPPNAME<br>snapcraft push --release=edge *.snap</pre><p>Then view your snap in the store <a href="https://snapcraft.io/store">https://snapcraft.io/store</a></p><h4>Pushing a stable release</h4><p>You need to push with the command parameter --release=stable (or no release parameter at all, as it defaults to stable) instead of--release=edge and you also must ensure that your snapcraft.yaml contains grade: stable not grade: devel</p><p>Thus:</p><p>snapcraft push *.snap</p><p>look at the number returned e.g. 2 and specify that in your next command</p><p>snapcraft release YOURAPPNAME 2 stable</p><p>Now your app is in the appstore as a stable release. Users can choose from a dropdown whether to install a stable release or an edge release.</p><h3>Part III — Debugging snaps</h3><p>I don’t know of a way to debug a deployed snap, you can only really debug the build process. If you get errors when building or debugging, there are different approaches.</p><p>When building, you might want to shell inside the VM if an error happens. You can do this during the build process by specifying snapcraft --shell-after and you will be dropped inside the VM. You can look in the prime directory to see what the final snap filesystem looks like. There are other directories here, which represent other stages of the build process. You can find more info <a href="https://stackoverflow.com/questions/43556433/snap-packages-what-is-the-purpose-of-the-staging-and-priming-steps">here</a>.</p><p>Whilst you can invoke Python inside the VM — for a GUI app that’s not going to do much good, because you cannot run GTK in a headless way. But you can run plain Python. However be warned that the PYTHONPATH is not set up properly, especially with regards to pointing to the site-packages directory inside the VM. You can however work around issues like this by specifying what you want PYTHONPATH to be on the same line as invoking Python:</p><pre>PYTHONPATH=/root/parts/rubber-band-async/install/lib/python3.6/site-packages/ python3 -c&quot;import wx&quot;</pre><p>The VM is not really meant to be a place you run things, its a place where things are built.</p><h4>A key insight and AHA! moment</h4><p>The next bit of information really helped me get an understanding of the movement of files and the whole snap workflow. Perhaps it will help you too.</p><p>The contents of a snap file are exactly what is in the virtual machine /root/prime build directory. You can look inside your .snap with unsquashfs -l *.snap|less which is great for seeing what files are where.</p><p>Thus, in a sense, the following are equivalent:</p><ul><li>$SNAP in the snapcraft.yaml file</li><li>/root/prime in the build VM</li><li>the root of the .snap file’s internal file hierachy / filesystem</li><li>squashfs-root/ of the .snap file’s internal file hierachy / filesystem when listing the snap contents with theunsquashfscommand</li><li>/snap/YOURAPPNAME/x3/ when the snap is installed on your Linux system. The x means <strong>local</strong> install, and the e.g.3 is the revision of the build, and <em>constantly increments</em></li></ul><p>When referring to $SNAP in snapcraft.yaml, you are referring to the /root/prime directory in the VM being used to build your snap file. Those /root/prime directory files are then copied into root of the filesystem inside the .snap being produced.</p><blockquote>I think the snapcraft documentation would benefit having this “directory equivalence information” in the documentation. It’s only after working and researching snaps for several days that you figure this stuff out — at least that’s what happened to me!</blockquote><p><strong>Update</strong>: As this <a href="https://forum.snapcraft.io/t/getting-ready-for-stable/4305/18">helpful post</a> points out, “the variable $SNAP is meant to be used <em>after installation</em> of your snap. It points to the directory of your snap <em>after it is installed</em>. You should not use it during build. These are some of the variables to use during build: <a href="https://snapcraft.io/docs/parts-lifecycle#heading--parts-directories">https://snapcraft.io/docs/parts-lifecycle#heading--parts-directories</a>.” Since the snapcraft stages are a little confusing, its sometimes hard to know what part of the snapcraft.yaml file is used in which stage. It seems to me that at the very least, launch commands that have an environment: entry could validly refer to the variable $SNAP because launching happens after everything is installed.</p><h4>Shell inside after the build is done</h4><p>Whilst you can’t look inside around the snap with a bash shell, now that we know what corresponds to what, we can do the next best thing and shell into the prime directory of the associated VM:</p><pre>multipass start snapcraft-pynsource<br>multipass shell snapcraft-pynsource<br>sudo bash<br>cd /root/prime</pre><pre># look around, use less and vi and ls etc...</pre><pre>exit<br>multipass stop snapcraft-pynsource</pre><p>Note I had to become root once inside, otherwise I couldn’t cd into the build result directory, viz. prime.</p><p>Remember though that usually, snapcraft --debugor snapcraft --shell-afteris a better way to get a bash shell, and drops you straight in, in the proper dir with proper permissions, but of course invoking via a snapcraft command does trigger a build — which if there is nothing to do, should be reasonably fast.</p><h4>Current directory</h4><p>The current directory from the point of view of a running snap is your actual host filesystem, not the secret filesystem inside the snap. This is as it should be.</p><p>If you want to access the secret filesystem inside the snap (for example to access some resource your program needs), your program can look at the environment variable SNAP and this will be set to the path you need to look in. See <a href="https://www.msweet.org/blog/2018-01-23-snaps-and-gui-apps.html">this article</a> for an example of some C code doing this. For Python you would</p><pre>if <strong>&quot;SNAP&quot; </strong>in os.environ:<br>    snap_root_dir = os.environ[<strong>&quot;SNAP&quot;</strong>]</pre><p>You can also use this technique from one of your Python files: os.path.dirname(os.path.realpath(__file__)).</p><h4>Debugging pushing up your snap</h4><p>If you push as <strong>edge</strong> and then later attempt to push <em>that same .snap file</em> as <strong>stable</strong>, or vice versa — the push will fail as the ‘binaries do not differ’ viz. A file with this exact same content has already been uploaded. Snapcraft say:</p><blockquote>This is “working as designed”. When you push a snap to the store, you can optionally “release” it to a channel. Once that snap is in the store you can later release it to another channel, no need to re-upload. The channel really is just a pointer. So to release to stable you’d “snapcraft release (snapname) (revision) (channel)”, e.g. “snapcraft release mysnap 3 stable”. This is instant, and doesn’t require a rebuild and re-upload.</blockquote><p>I’ve run in to the issue a few times where I accidentally push my edge .snap with the release parameter set to stable, which rightly gets rejected (the release is rejected, not the push).</p><pre>Revision 6 of &#39;andy-testsnap-py&#39; created.</pre><pre>invalid-field: Revision 6 (strict) cannot target a stable channel (stable, grade: devel)</pre><p>Attempting to correct my mistake with another push &amp; release — this time to edge — annoyingly gets rejected because it’s already uploaded.</p><blockquote>Why can’t the push just fail silently and move on with the release part of the command — why crash out?</blockquote><p>To get around this, I used to make a small change in either my code or the snapcraft.yaml file (to make the snaps binaries different), rebuild my snap, push and release again. It turns out that this is unnecessary. Since the binary is already pushed and living in ‘purgatory’ (neither edge or stable) you can still release it with a simple, fast release command e.g.</p><p>snapcraft release andy-testsnap-py 6 edge</p><p>The number 6 comes from the previous push command and is the revision of the snap. Each time you push a snap or each time you install a snap locally, the revision increments — so keep a close eye on those revision numbers!</p><h4>Debug via sub-command scripts</h4><p>A snap can have more than one entry point. This is really useful for debugging because you can add additional helper scripts to debug or support your main app.</p><blockquote>You can actually have multiple command entry points to your app.</blockquote><p>Assuming you have called your app YOURAPPNAME you invoke these sub entry points using the name of your YOURAPPNAME.subcommand, using the terminal. E.g.</p><pre>$ YOURAPPNAME<strong>.report<br></strong>$ YOURAPPNAME.<strong>subcommand2</strong></pre><p>All commands entry points live under the apps: sections of your snapcraft.yaml.</p><pre>apps:<br>    YOURAPPNAME:<br>        command: desktop-launch python3 $SNAP/YOURAPPMAIN.py</pre><pre>    <strong>report</strong>:<br>        command: python3 $SNAP/report_snap_env.py</pre><pre>    <strong>subcommand2</strong>:<br>        command: python3 $SNAP/whatever.py</pre><p>The first entry point YOURAPPNAME in the snapcraft.yaml file under the apps: section is your main entry point viz. invoked via$ YOURAPPNAME. The rest are optional ‘sub’ entry points.</p><p>If you want to tweak your PYTHONPATH or PATH then simply add an environment section beneath each command e.g.</p><pre>apps:<br>    ....<br>    report-add-site:<br>        command: python3 $SNAP/report_snap_env.py<br>        <strong>environment:<em><br>          </em>PYTHONPATH: $PYTHONPATH:$SNAP/lib/python3.6/site-packages</strong></pre><p>The above environment command is actually unnecessary since site-packages is added automatically when running a Python script. Both the $SNAP directory (which is the root of the deployed snap filesystem, and typically the root of your source code) and the Python site-packages directory are automatically added to PYTHONPATH, as you would expect — without you needing to mess with having an environment section like this.</p><p>I shipped a custom python script called report_snap_env.py with my snap project</p><blockquote>A star trek ‘probe’ command :-)</blockquote><p>and exposed it via a sub-command called report (again, arbitrary name) in order to see the environmental situation I am dealing with when running a snap. See the above snapcraft.yamlfragment to see how I expose this python script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/537c8a1aeb6a9ab70874fa6632b2e8d2/href">https://medium.com/media/537c8a1aeb6a9ab70874fa6632b2e8d2/href</a></iframe><p>Then, after installing the snap, running YOURAPPNAME.report instead of running the usual YOURAPPNAME, in a terminal, runs my report_snap_env.py script and tells me what is going on with the Python environment inside the snap, which I find useful.</p><p>The output will appear in the Linux terminal via regular print commands. Run snap list to ensure your snap is installed locally on your development machine. Add as many diagnostic or supplementary scripts as you like, using this technique.</p><h3>Part IV — Troubleshooting and Snapcraft Bugs</h3><h4>Multipass</h4><p>The snapcraft technology builds via virtual machines managed by multipass. These VMs don’t have any GUI and are reasonably slim, compared to the usual VM you run in GUI mode using Vmware or Virtualbox.</p><p>Running snapcraft should install multipass for you, when needed. You will usually not need to run multipass commands but its handy to know a few key commands. To list all your virtual machines used for building snaps, multipass listand use start and stop to manage them.</p><pre>multipass list<br>multipass start snapcraft-pynsource<br>multipass stop snapcraft-rubber-band-async</pre><p>You may find it useful to shell into a VM using multipass shell YOURVMNAME e.g. multipass shell snapcraft-rubber-band-async. Then you get a bash prompt and can look around. You should find the prime snap build directory via cd /root/prime though you will need to sudo bash first. Sure, the snapcraft --shell-after is more convenient because it drops you in the correct directory and there are no permission problems, but its only available during a snapcraft build, whereas using multipass shell can be issued at any time to peek inside any VM you have lying around.</p><h4><strong>Troubleshooting multipass</strong></h4><p>There are various bugs I encountered with Multipass:</p><ul><li>The multipass virtual machine system has a bug where it randomly stops responding to snapcraft, giving timeouts, which means the snapcraft command sometimes fails. E.g. you get a <br>list failed: cannot connect to the multipass socket<br>error or other <strong>various timeout errors</strong>. Perhaps it was my VM. The solution seems to be one or more of the following</li><li>1) simply wait for a while and retry the snapcraft command</li><li>2) use multipass list to view the running VMs or VMs that are in delayed shutdown mode, shut them down manually with e.g. multipass stop snapcraft-andy-py-cli then try running snapcraft again</li><li>3) restart multipass with snap restart multipass. More detail: After reporting <a href="https://github.com/CanonicalLtd/multipass/issues/683">this issue</a> in the multipass project on Github, I got some assistance and the suggested workaround is to stop any multipass VMs (list them with multipass list) with multipass stop your_vm_name, finally followed snap restart multipass. Thensnapcraft hopefully runs ok.</li><li>4) Other possible solutions mentioned <a href="https://github.com/CanonicalLtd/multipass/issues/460">here</a>.</li><li>Multipass sometimes gives errors the first time you use it. Issues <a href="https://forum.snapcraft.io/t/building-for-core18-multipass-issue/8958/20">here</a> and <a href="https://bugs.launchpad.net/snapcraft/+bug/1813979">here</a>. They seem to settle down after you runmultipass launch snapcraft:core18. If not, there are several other debugging commands you can run, listed <a href="https://github.com/CanonicalLtd/multipass/issues/683#issuecomment-473820911">here</a>.</li></ul><p>If desperate, you can always uninstall and re-install multipass (I’ve been down this road). Linux: snap remove multipass. Since you can build snaps on a Mac (cos building is virtual machine based) here are the uninstall instructions for Mac: sudo sh /Library/Application\ Support/com.canonical.multipass/uninstall.sh followed by brew uninstall snapcraft. To install multipass again, simply run the snapcraft command — on Mac and Linux multipass will be automatically installed as needed. Alternatively, run sudo snap install multipass --beta --classic (on Linux).</p><h4>How to do snapcraft development inside a Linux Virtual Machine</h4><p>This is mainly what I do. My iMac is my host machine, and I run Ubuntu 18.04 inside Vmware. Ironically within my Linux world, snapcraft uses multipass virtual machines. So that’s virtual machines within a virtual machine :-)</p><p>You can even build linux .snap releases on a Mac, because it is all virtual machine driven. A windows version of snapcraft is coming too.</p><p>Note that if you are trying to run snapcraft inside Linux inside a virtual machine, you must use Vmware not Virtualbox. This is because the multipass VM technology relies on some hypervisor feature that only Vmware supports. Configure your Ubuntu 18 Linux VM like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*n6V7s1o1JTcRXdYK6HAVQQ.png" /><figcaption>The needed hypervisor setting for Vmware</figcaption></figure><p>Update: Snapcraft have told me that an upcoming release of snapcraft will fix this issue, to make it easier to build snaps inside VMs you already have.</p><h4>Snapcraft Bugs</h4><p>I ran into my share of bugs — a minefield of them. It is March 2019 as I write this. Though, it is possible to navigate through them and build and publish a snap — so, don’t give up!</p><ul><li>A snap built on Ubuntu 18.04 would not install on the Ubuntu 16.04 LTS using the app store — it is only possible via terminal commands e.g. sudo snap install pynsource. See <a href="https://forum.snapcraft.io/t/core18-classic-snap-cant-be-installed-via-the-ui-on-16-04-how-to-build-one-that-can/10293/7">this issue</a>. I would have thought that one of the primary purposes of snaps is that they can install in multiple versions of Linux, so</li></ul><blockquote>It’s ironic/sad that a snap built in Canonical’s Ubuntu 18.04 cannot be installed via the UI app store in their own product, Ubuntu 16 LTS.</blockquote><ul><li>Installing a snap on the older Ubuntu 16.04 LTS (long term support) via <em>terminal</em> luckily <em>does</em> work but currently requires an extra command sudo snap install core to compensate for a bug where a needed ‘core’ snap is not automatically downloaded as a dependency. See <a href="https://forum.snapcraft.io/t/core18-snap-fails-to-run-on-16-04-cannot-locate-the-core-snap/10292/3">this issue</a>.</li><li>Using version of Python other than the default Python 3.6.7 that comes with Ubuntu 18 is not documented. Vague references to Python 3.7 ‘snaps’ lead to an <a href="https://forum.snapcraft.io/t/classic-confinement-request-for-python37-snap/3808">abandoned project</a>, and whilst a forum question helpfully points to an example snapcraft.yaml — its part of a larger complex project and its not clear how to extract the needed Python 3.7 bit of the snapcraft.yaml, let alone how it would interact and coordinate with the wxPython install stage (which is Python version specific). I’m still to follow up on this. This should be documented clearly with examples IMO. See <a href="https://forum.snapcraft.io/t/build-a-snap-with-any-version-of-python-i-want/10420">this issue</a>.</li><li>The huge <a href="https://kyrofa.com/posts/develop-your-snaps-faster">workflow speedup</a> of using the command snap try prime/ is broken with core18 based snaps, (and ironically, core18 are the <em>recommended</em> snaps). Sigh.</li></ul><blockquote>Needing to invoke ‘snapcraft clean&#39; a lot — results in a painful re-download of what seems like the entire Ubuntu VM and associated libraries which can take over an hour per build</blockquote><ul><li>Snapcraft is pretty smart about only rebuilding what it needs to. However, too often a you are forced to do a snapcraft clean before building a .snap via thesnapcraft command. This results in a painful re-download of what seems like the entire Ubuntu VM and associated libraries which can take an hour (in my Vmware VM on a powerful iMac host, with fast broadband internet). Annoyingly, I am <strong>forced</strong> to do snapcraft cleanbecause of bugs in the Python plugin — see the <a href="https://bugs.launchpad.net/snapcraft/+bug/1820843">pip not found bug</a> or <a href="https://forum.snapcraft.io/t/error-you-must-give-at-least-one-requirement-to-install-when-rebuilding-parts-with-python-plugin/9011">must give at least one requirement bug</a>. The status of the latter bug is “Can anyone that speaks Python look into it?” as of Dec 2018.</li><li>Whilst the snapcraft command supposedly supports partial cleaning (thus supposedly avoiding the wasteful, one hour, starting from scratch process of the brutal snapcraft clean), the more nuanced snapcraft clean -s is actually broken <a href="https://forum.snapcraft.io/t/snapcraft-clean-why-error-no-such-option-s/10460">see this issue</a> which a Snapcraft employee has confirmed is a bug, for core18 based snaps, which ironically are the recommended snaps!</li></ul><h3>Conclusion</h3><p>It feels really satisfying to have successfully built a snap. I feel like I’ve been through a quest where everything that can go wrong has gone wrong. But hey — that’s programming, and to a lesser degree: that’s open source and that’s Linux. Hopefully this article helps Python developers get a wxPython GUI app into the Ubuntu/Canonical/Snapcraft app store.</p><p>Please check out my <a href="http://pynsource.com/">Pynsource</a> UML reverse engineering tool for Python on the Snapcraft Pynsource app store page <a href="https://snapcraft.io/pynsource">here</a> !</p><h3>My Other Cool Software</h3><ul><li><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*v2ecMpZhMtQIudbiR_ssHQ.gif" /><figcaption><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app). A revolution in documentation — diagrams automatically update when you push code using git</figcaption></figure><ul><li><a href="http://pynsource.com/">Pynsource</a> — UML for Python (desktop app)</li><li><a href="https://pyrpn.atug.com/">Python to RPN</a> — Run Python 3 on vintage HP calculators (web app)</li><li><a href="https://print42.atug.com/">Print42</a> — Electron-Python app, non-invasive log file annotation tool that supports thermal printers</li></ul><h3>About Andy Bulka</h3><ul><li>Main website and blog <a href="http://www.andypatterns.com/">www.andypatterns.com</a></li><li>Medium article: <a href="https://medium.com/@abulka/electron-python-4e8c807bfa5e">Building a deployable Python-Electron App</a> — Using Electron as a GUI toolkit for Python.</li><li>Medium article: <a href="https://medium.com/@abulka/async-await-for-wxpython-c78c667e0872">Async/await for wxPython</a> — Python 3 GUI apps with asynchronous functionality.</li><li>Medium article: <a href="https://medium.com/@abulka/getting-python-and-wxpython-apps-into-the-ubuntu-app-store-ccca7ae537a3">Getting Python and wxPython apps into the Ubuntu app store</a></li><li>Github <a href="https://github.com/abulka?tab=repositories">https://github.com/abulka</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccca7ae537a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async/await for wxPython]]></title>
            <link>https://medium.com/@abulka/async-await-for-wxpython-c78c667e0872?source=rss-4c66d4d2dfca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c78c667e0872</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[uml]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[wxpython]]></category>
            <dc:creator><![CDATA[Andy Bulka]]></dc:creator>
            <pubDate>Sat, 02 Mar 2019 03:28:56 GMT</pubDate>
            <atom:updated>2019-08-29T23:18:32.733Z</atom:updated>
            <content:encoded><![CDATA[<h4>Python 3 GUI apps with asynchronous functionality</h4><p>Python 3’s support of async/await is the new hotness, allowing cooperative computation with reduced complexity and without needing threads — as long as you use async compatible libraries like <a href="https://aiohttp.readthedocs.io/en/stable/">aiohttp</a> etc. You can’t use the famous <a href="http://docs.python-requests.org/en/master/">requests</a> library because it is not async aware and will block, but not to worry, those other libraries have you covered.</p><p>The <a href="https://wxpython.org/">wxPython</a> project is a wonderful, full featured cross-platform GUI toolkit that is completely free to use in commercial projects — unlike some (cough, cough, umm, PyQt). Wouldn’t it be great if you could utilise async/await in wxPython? This would be great for the usual reasons:</p><ul><li>checking a server for information, in the background</li><li>running a long process without locking up the UI</li><li>etc</li></ul><blockquote>Well it seems you are out of luck, because wxPython already comes with its own messaging event loop, and you can’t have two event loops — can you?</blockquote><p>By two event loops, I mean the Python 3 <a href="https://docs.python.org/3/library/asyncio-task.html#id3">asyncio event loop</a> and the <a href="https://wxpython.org/Phoenix/docs/html/wx.App.html#wx.App.MainLoop">wxPython </a>main GUI <a href="https://wxpython.org/Phoenix/docs/html/wx.App.html#wx.App.MainLoop">event loop</a>.</p><h3>Blending event loops</h3><p>I remember running into this problem a decade ago where I wanted to blend wxPython widgets into <a href="https://www.pygame.org/">PyGame</a> and both had their own event loops. Some interesting <a href="https://wiki.wxpython.org/IntegratingPyGame">initial approaches</a> were unsatisfactory so I ended up writing a meta-event loop that did a bit of wxPython and a bit of PyGame — giving them both a chance to run. I never published the code, but it worked.</p><p>Then when listening to <a href="https://pythonbytes.fm/episodes/show/119/assorted-files-as-django-orm-backends-with-alkali">an episode</a> of the wonderful podcast <a href="https://pythonbytes.fm/">Python Bytes</a>, the topic of introducing asyncio to the PyQt GUI toolkit came up — again the solution has been to blend event loops — see <a href="https://github.com/gmarull/asyncqt">asyncqt</a>.</p><p>Whilst listening to the above podcast, it struck me as coincidental because I’ve recently been utilising a similar project for wxPython called <a href="https://github.com/sirk390/wxasync">wxasync</a> which blends the wxPython event loop with Python 3’s asyncio loop. Result? I can now use Python 3’s async/await with wxPython!</p><blockquote>wxasync is a library for using Python 3 asyncio (async/await) with wxPython.</blockquote><p>A trio of similar solutions!</p><h3>Benefits to my project — Pynsource</h3><p>The ability to have asynchronous methods in my Python UML tool <a href="http://bit.ly/pynsource">Pynsource</a> has been a boon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*H4o2o7kq_B1wT4gGk3pdMw.png" /><figcaption><a href="http://bit.ly/pynsource">Pynsource UML for Python</a> is now using async/await</figcaption></figure><p>I recently upgraded the entire open source <a href="http://bit.ly/pynsource">Pynsource</a> codebase to Python 3. Beside being a prudent upgrade, it has allowed me to be able to parse and reverse engineer <strong>Python 3</strong> source code into UML class diagrams. Actually Pynsource can still parse <strong>Python 2</strong> because I switched to the <a href="https://pypi.org/project/typed-ast/">typed-ast parser</a>, which only runs under Python 3, and has the advantage of being able to parse either syntax. In fact, <a href="https://discuss.python.org/t/merge-typed-ast-back-into-cpython/377/28">Guido himself</a> worked on this module recently.</p><p>Now that Pynsource was converted to Python 3, I wanted to take advantage of all that async/await goodness. :-)</p><h4>Background app version check</h4><p>The first thing I added was a new background version check function, to notify users when a new version of Pynsource was available. I now check a server for the latest version — in the background, a few seconds after startup — without affecting the UI.</p><h4>Background http request to render PlantUML</h4><p>Asynchronous programming also helped enormously with a new feature of Pynsource which is the ability to reverse engineer Python and render a <a href="http://plantuml.com/class-diagram">PlantUML</a> class diagram image. This involves calling an internet based rendering service which can take some time to run, depending on the complexity of the UML class diagram you are trying to generate.</p><blockquote>My initial implementation blocked whilst waiting for the server response and the user had to wait - the UI was unresponsive. Not a good look.</blockquote><p>After importing wxasync and converting my code to use async/await, the PlantUML rendering in Pynsource is now non-blocking. This is a much better user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSeFZPAc-g32Hz3E51Z-ag.png" /><figcaption>Pynsource rendering UML but GUI is still responsive</figcaption></figure><p>This also allowed me to implement a cancel feature: hittingESC will cancel the render, just in case it is taking too long or has locked up. Wonderful!</p><p>I even have a seconds counter in the status bar telling you how much time the internet call is taking. The counter is only possible because of async/await. The resulting PlantUML diagram soon arrives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M4X-yTk6z6ccUS9soxHTQ.png" /><figcaption>Final image retrieved from the server</figcaption></figure><h3>How to convert your wxPython app to use wxasync</h3><p>You should be able to convert any existing wxPython application to use wxasync as long as it is written in Python 3 of course, since the async/await technology is only available in Python 3.5 and later.</p><p>You should probably learn a little about the async/await approach before attempting this — there is a bit of a learning curve getting your head around this stuff. There are <a href="https://www.google.com/search?ei=7sJ4XNOcCMb59QOqspfYDg&amp;q=async%2Fawait+python+3+tutorials&amp;oq=async%2Fawait+python+3+tutorials&amp;gs_l=psy-ab.3..0i22i30.5352.10898..11031...0.0..0.214.1924.0j10j1......0....1..gws-wiz.......0i71j35i39j0i22i10i30j0i13i30.jU7yLYYwC-k">plenty of tutorials</a> on it when you search.</p><blockquote>I’ll be bold and try to sum up async/await up in a single paragraph:</blockquote><p>Instead of traditionally invoking your Python program to run from top to bottom you must invoke it via a special loop which runs forever or till your program exits. Inside the loop, your code will run from top to bottom as usual but if you call an async function containing an await call to a long running function (e.g. a http request via aiohttp), your code yields to the main loop — allowing the loop to try to run other tasks. Tasks are just another name for these async functions that are in various states of suspension. It’s a cooperative thing — no threads or interrupts. When your code reaches the bottom, it of course stops and the only remaining code that will run in the cooperative loop are any leftover async tasks/functions. In the case of wxPython, you never reach the bottom of your code — the wxPython event loop runs forever, till you explicitly exit.</p><p>I’m definitely not an async/await expert, so apologies for any inaccuracies in my summation, above. It’s just meant to be an explanatory perspective that may help some Python programmers grok the idea. Remedial and official doco on Python 3 async/await event loops is <a href="https://docs.python.org/3/library/asyncio-eventloop.html">here</a> and broader official async/await doco is <a href="https://docs.python.org/3/library/asyncio-task.html">here</a>.</p><h4>Step 1</h4><p>The first thing you do is import wxasync and change your app to subclass from WxAsyncApp instead of the traditional wx.App</p><pre>from wxasync import AsyncBind, WxAsyncApp, StartCoroutine</pre><pre>class MainApp(WxAsyncApp):<br><em># class MainApp(wx.App):</em></pre><p>Then instead of starting your app with</p><pre>def main():<br>    application = MainApp(0)<br><em>    </em>application.MainLoop()</pre><p>you start it with</p><pre>from asyncio.events import get_event_loop</pre><pre>def main_async():<br><em>    </em>application = MainApp(0)<br>    loop = get_event_loop()<br>    loop.run_until_complete(application.MainLoop())</pre><h4>Step 2</h4><p>You should now be able to call async functions or methods, and still have the wxPython GUI remain responsive. For example here is my call to trigger the check for the latest version of my program — which happens in during app startup in OnInit():</p><pre>StartCoroutine(self.check_for_updates, self)</pre><p>The “coroutine” being called is simply my async function check_for_updates which first sleeps for a while using await asyncio.sleep(15), so that the version check doesn’t happen straight away and annoy the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58df55b3e15adfd83ee7eff6c918a1bd/href">https://medium.com/media/58df55b3e15adfd83ee7eff6c918a1bd/href</a></iframe><p>Note that check_for_updates does not use the requests package to retrieve the url, it instead uses a call to my function url_to_data which uses aiohttp. Yeah, the syntax of theurl_to_datafunction is a bit gnarly but it does the job and I don’t have to think about it, now that it is written — it grabs the contents of a url, asynchronously, which means it yields to the wxasync event loop whilst waiting for the server response, allowing both wxPython and Python 3 tasks to have a bit of cpu time.</p><p>Notice that I had to explicitly decode the server response text from utf-8 before accessing it as a Python string.</p><p>Notice also that I cache the call to the server, so that next time, the server call is avoided for the same rendering job. I had to use a special version of lru_cache namely <a href="https://github.com/aio-libs/async_lru">async_lru</a> since the standard Python <a href="https://docs.python.org/3/library/functools.html">lru_cache</a> does not work with async functions.</p><h3>Rubberband app</h3><p>Here is a fun wxPython app that uses async/await. You drag the mouse to create a selection rectangle. Note that at some point in the demo, I right click the mouse to start the async timer which displays in the status bar. The timer runs independently and asynchronously whilst I am dragging in the GUI — nice!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sxvL3zUqsBcP7aCuJNK79w.gif" /><figcaption>Fun asynchronous “rubber band” wxPython app</figcaption></figure><p>The full source code to this app is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42fa7148f285e0228b55d4241bb3e848/href">https://medium.com/media/42fa7148f285e0228b55d4241bb3e848/href</a></iframe><h3>Other asynchronous approaches</h3><p>To be fair, there are a few things you can do in wxPython to “loosen up” the event loop without using async/await.</p><p>You can call wx.SafeYield() at any time which allows the main wxPython event loop to “breathe” and process GUI events. However you can soon get into recursion problems if another wx.SafeYield() happens during the wx.SafeYield(). Plus you are not taking advantage of async/await and all the libraries that support it. Still, I use this approach during my diagram layout so that the incremental results of layout animate for the user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iovEeu1dJLikeZUHTXuY4A.gif" /><figcaption>Layout Animation using wx.SafeYield() in Pynsource</figcaption></figure><p>You can also use wx.<a href="https://wxpython.org/Phoenix/docs/html/wx.functions.html#wx.CallAfter">CallAfter</a> which queues a regular function or method to be run next time the wxPython loop gets a chance. That’s cooperative, like async/await is.</p><p>Then there are threads. There is a portion of my Pynsource app which does not use async/await during a long task — it uses threading. That is the <strong>deep layout</strong> algorithm feature for “laying out” UML diagrams more optimally. This works like normal layout but runs for longer, running the entire layout several times, using different parameters, then chooses the “best looking” layout. This takes several seconds to run and “think”.</p><p>Of course I wanted to run this deep layout and not lock up the GUI — the only solution five years ago was threading. It got a little complex and you can look at the <a href="https://github.com/abulka/pynsource">Pynsource GitHub source code</a> to see how I did it. It was based on the wxPython article on <a href="http://wiki.wxpython.org/LongRunningTasks">long running threads</a>. Using wxasync is much easier to use than background threads and CallAfter’s. Presumably I could now revisit that code and use async/await instead — or I could just leave it, as it isn’t broken. :-)</p><h3>Is async/await an anti-pattern?</h3><p>Are there any downsides to async/await? Surely not.</p><p>Yet soon I hit a conceptual brick wall — it startled me and got me researching... It turns out that async/await has been around in other languages for <a href="https://en.wikipedia.org/wiki/Async/await">a long time</a></p><blockquote>The feature is found in C# 5.0, Python 3.5, Hack, Dart, Kotlin 1.1, and JavaScript, with some experimental work in extensions, beta versions, and particular implementations of Scala[1], Rust[2], and C++.</blockquote><p>time enough for “real world” news from the trenches to emerge. Sure enough, googling around, I found that the brick wall I hit was a common problem which I call the <strong>“turtles all the way up”</strong> problem:</p><blockquote>Anything calling an async function must also be marked with the async keyword. And so on. This can get out of control and spread through a codebase like wildfire.</blockquote><p>For example, when I implemented the async loading of a particular http resource deep down in my app, I was forced to declare async/await all the way up my call hierarchy. At first, I started complying — just to get the thing to work, but after I’d added a dozen async calls I still wasn’t finished — so I stopped and regrouped. Something was wrong.</p><p>Some <a href="https://hackernoon.com/controlling-python-async-creep-ec0a0f4b79ba">have criticised</a> async/await as an anti-pattern for this very reason. The the <a href="https://en.wikipedia.org/wiki/Async/await">wikipedia article on async/await</a> refers to this phenomenon as a “zombie virus” — though mitigates this inflammatory description with the explanation:</p><blockquote>it has been argued that this contagious nature of the code (sometimes being compared to a “zombie virus”) is inherent to all kinds of asynchronous programming, so await as such is not unique in this regard…</blockquote><h4>My “turtle avoidance” solutions</h4><p>If you don’t mind the async keywords spreading through your codebase, or you can control its spread, then that’s great.</p><p>If however you have an existing app and you simply want to make a few key portions asynchronous without too much contagion of the async keyword and the async/await paradigm, then read on.</p><p>My two solutions revolve around the premise that often <strong>you don’t need to wait for the result</strong>, especially in a wxPython GUI context. Like when checking for a response from a server regarding what the latest version of your wxPython app is, so that the user can be notified of upgrades. The user doesn’t care when the notification message appears. So you don’t need to await. Luckily wxasync provides a method called StartCoroutine()which lets you call an async function without awaiting it.</p><p>Let’s review the important wxasync imports:</p><pre>from wxasync import AsyncBind, WxAsyncApp, StartCoroutine</pre><ul><li>AsyncBind—is an alternative to wxPython Bind() and is there to trigger an async method instead of a normal method, from an event (like a button click, mouse move or menu item click).</li><li>WxAsyncApp we have already talked about — it’s the fundamental way you instantiate your wxPython application if you want to use async/await.</li><li>And StartCoroutine()is how you can trigger an async function, otherwise you would have to await it.</li></ul><h4>Solution 1 — StartCoroutine()</h4><p>So instead of async/await calls all over the place, it often might be enough for some bit of code to call the wxasync library’s method StartCoroutine(), thereby work happens and the GUI is still responsive. In fact the main <a href="https://github.com/sirk390/wxasync">wxasync example on their GitHub page</a> demonstrates this approach. You simply trigger StartCoroutine() calls from any normal bit of wxPython code — even code triggered from button clicks bound with regular wxPython Bind. Nice. There is no need to use the async/await keyword, except for the async on the coroutine function itself, and presumably an await inside that coroutine. Thus no danger of async/await keywords spreading through any call stack.</p><h4>Solution 2— Raise a custom event</h4><p>The second variant of this idea has the same premise, but a different implementation approach. You generate a custom wxPython event and emit it from any place in your code base, to trigger an async method which is bound to that custom event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deaeccbdc871b7f73ca48d6f70855c46/href">https://medium.com/media/deaeccbdc871b7f73ca48d6f70855c46/href</a></iframe><p>See below for a full code sample. With this approach, any “normal” synchronous code can emit this event, and there is no need to contaminate your codebase with async/await keywords, except for the final async function doing the work.</p><blockquote>In a sense, the use of an event (or a call to StartCoroutine) decouples and breaks the turtle hierarchy — as long as you don’t have to wait for the result.</blockquote><p>If you do need to wait for the result, then you are back to the turtle problem again. The asynchronous use cases in my application Pynsource have so far gotten away with not needing to wait for the final asynchronous result. For example when a user switches to the “PlantUML” tab to see their UML diagram rendered as a PlantUML diagram image — the user can either watch and wait, or do other things in Pynsource whilst they are waiting, or hit ESC to abort at any point. The premise of “not needing to wait for a result” is satisfied, so luckily, I avoided the “turtles all the way up” problem in this case.</p><p>Of course I <strong>do</strong> have several call layers of async/await involved in my PlantUML rendering functionality — the point is, its isolated.</p><h3>Another complete code example</h3><p>Here is another complete wxPython app using wxasync and Python 3 — a more technical demo, which demonstrates async/await functionality and also shows the use of:</p><ul><li>Using wxasync with wxPython</li><li>Using AsyncBind</li><li>Calling coroutines</li><li>Raising custom events</li><li>Lots of async goodness</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SvXLNzOEE9hZi6OqBwekg.png" /></figure><p>The buttons in the demo GUI app do the following, starting from top to bottom:</p><ul><li>Button click triggers an async method which displays messages. The display of messages is asynchronous, and GUI buttons are still active.</li><li>Button click triggers an async method which is a Coroutine which loops forever or until the button is pressed again, showing a clock ticker at the bottom of the frame.</li><li>Button click triggers an event, which is bound to a normal synchronous method which displays messages. Note the GUI becomes unresponsive and the clock ticker halts until the messages stop.</li><li>Button click triggers an event, which is bound to an asynchronous method which displays messages asynchronously. Note the GUI and the clock ticker are still responsive.</li><li>Button click causes another popup frame to appear. You can close this. The purpose of this was to debug wxasync when using multiple wxPython frames. Ensure you are using the latest version of wxasync to avoid exceptions when closing frames.</li></ul><p>This code requires Python 3, wxasync (pip install wxasync) and wxPython (pip install wxPython), which happens to be Phoenix 4.04 as of the writing of this article. It runs on Mac, Windows and Linux. For Linux, to install wxPython, you will need to target a wheel specific to match your version of e.g. Ubuntu e.g. pip install -U -f <a href="https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04">https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04</a> wxPython see official wxPython installation instructions <a href="https://wiki.wxpython.org/How%20to%20install%20wxPython#Installing_wxPython-Phoenix_using_pip">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2622661f5eab0c7c08177e84d34fd312/href">https://medium.com/media/2622661f5eab0c7c08177e84d34fd312/href</a></iframe><h3>Final Words</h3><p>The ability to use Python 3 asynchronous programming in wxPython has been a wonderful success. There is nothing worse than a GUI app “locking up” during long processes.</p><p>I hope you found this article useful. If you are a Python developer, please check out <a href="http://bit.ly/pynsource">Pynsource</a> my open source UML reverse engineering and UML class diagramming tool — and experience the power of a wxPython async application!</p><h3>My Other Cool Software</h3><ul><li><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*v2ecMpZhMtQIudbiR_ssHQ.gif" /><figcaption><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app). A revolution in documentation — diagrams automatically update when you push code using git</figcaption></figure><ul><li><a href="http://pynsource.com/">Pynsource</a> — UML for Python (desktop app)</li><li><a href="https://pyrpn.atug.com/">Python to RPN</a> — Run Python 3 on vintage HP calculators (web app)</li><li><a href="https://print42.atug.com/">Print42</a> — Electron-Python app, non-invasive log file annotation tool that supports thermal printers</li></ul><h3>About Andy Bulka</h3><ul><li>Main website and blog <a href="http://www.andypatterns.com/">www.andypatterns.com</a></li><li>Medium article: <a href="https://medium.com/@abulka/electron-python-4e8c807bfa5e">Building a deployable Python-Electron App</a> — Using Electron as a GUI toolkit for Python.</li><li>Medium article: <a href="https://medium.com/@abulka/async-await-for-wxpython-c78c667e0872">Async/await for wxPython</a> — Python 3 GUI apps with asynchronous functionality.</li><li>Medium article: <a href="https://medium.com/@abulka/getting-python-and-wxpython-apps-into-the-ubuntu-app-store-ccca7ae537a3">Getting Python and wxPython apps into the Ubuntu app store</a></li><li>Github <a href="https://github.com/abulka?tab=repositories">https://github.com/abulka</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c78c667e0872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a deployable Python-Electron App]]></title>
            <link>https://medium.com/@abulka/electron-python-4e8c807bfa5e?source=rss-4c66d4d2dfca------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e8c807bfa5e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[thermal-printing]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Andy Bulka]]></dc:creator>
            <pubDate>Wed, 03 Oct 2018 03:49:33 GMT</pubDate>
            <atom:updated>2019-12-15T02:05:29.874Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a normal, deployable application for Mac or Windows, using Python 3 is hard. There is nothing like Visual Studio or Delphi (remember that?) for Python where you can drag and drop to design a GUI, press a button and get an .exe or .app to give people. Sad.</p><p>The closest you can get is to follow a long recipe of steps — which I propose to outline here. But first you have to choose a GUI toolkit for Python. Many programmers — including me — consider Python GUIs and associated deployment/packaging technology to be lacking. I’ve used wxPython in the past (see my <a href="http://bit.ly/pynsource">Pynsource UML tool</a> — reverse engineer Python into UML class diagrams), and thought I’d try the Chrome browser based <a href="https://electronjs.org/">Electron</a> as my front end for my latest project.</p><p>What’s that you hear — Electron? Yep.</p><blockquote>Electron is a framework for creating cross-platform native applications with web technologies like JavaScript, HTML, and CSS.</blockquote><p>One of the great things about using Electron as a GUI for Python is that you get to use cutting edge web technologies and you don’t have to learn some old, barely maintained GUI toolkit — in fact you can re-use your existing JavaScript, HTML, and CSS knowledge that you already use everyday for building websites.</p><p>Let me ask you this: How much momentum, money $$$$, time and how many developer minds are focused on advancing web technologies? Answer: it’s staggeringly huge. Compare this with the number of people maintaining old toolkits from the 90’s e.g. wxPython? Answer: perhaps one or two people in their spare time. Which would you rather use? You get the idea.</p><p>In addition to having a GUI that potentially displays everything you have ever seen rendered in a web page, using Electron as a GUI toolkit gets you</p><ul><li>native menus, notifications</li><li>installers, automatic updates to your app</li><li>debugging and profiling that you are used to, using the Chrome debugger</li><li>ES6 syntax (a cleaner Javascript with classes, module imports, no need for semicolons etc.). Squint, look sideways, and it kinda looks like Python… ;-)</li><li>the full power of <a href="https://nodejs.org/en/">nodejs</a> and its huge <a href="https://www.npmjs.com/">npm package repository</a></li><li>the large community and ecosystem of Electron</li><li>the ability to use tens of thousands of Javascript plugins and JavaScript UI widgets and controls e.g. <a href="http://jqueryui.com/">jQuery UI</a>, <a href="https://webix.com/">Webix</a> widgets, <a href="https://www.telerik.com/kendo-ui">Kendo</a>, <a href="https://www.chartjs.org/">Chartjs</a> for Charting and various <a href="https://www.creativebloq.com/design-tools/data-visualization-712402">visualisation</a> plugins — the possibilities are endless and exciting</li><li>In a sense, Google and tens of thousands of developers working on improving your GUI toolkit every day, every hour</li></ul><p><a href="https://github.com/fyears/electron-python-example"><strong>Electron Python</strong></a> is a template of code where you use <a href="https://electronjs.org/">Electron</a> (nodejs + chromium) as a GUI talking to Python 3 as a backend via zerorpc. Similar to <a href="https://github.com/ChrisKnott/Eel">Eel</a> but much more capable e.g. you get proper native operating system menus — and users don’t need to have Chrome already installed. It’s been around for a while and recently I decided to give it a try. Don’t be put off by the need to use a specific version of nodejs — I was able to use the latest nodejs and Electron.</p><p>I built and released both a Windows and Mac version of my app. It was a bit of a laborious road and this is an attempt at documenting my journey, so that you too can create a real, cross-platform, downloadable product with a nice GUI, in Python 3.</p><h3>Proof it works</h3><p>The Electron-Python app that I developed and deployed is called <a href="http://bit.ly/print42atug"><strong>Print42</strong></a> — check it out, incl. videos and screenshots at <a href="http://bit.ly/print42atug">http://bit.ly/print42atug</a>.</p><p>Print42 is a developer tool — a GUI app for tailing log files onto an onscreen printer tape. The key here is that the onscreen tape is writable, for dumping screenshots and text fragment notes into that same log file tape — without affecting the original log file on disk. Screenshots and text annotations are inserted into the “tape” and interspersed with the live log file entries. You can then scroll back and see your screenshots and notes and log entries. In essence you are “annotating” your log file with rich,helpful information — without affecting it, giving context and meaning to points in time in the log file, for better subsequent analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGZUUPcdMeSXo5d016bcxg.png" /><figcaption>Print42 built with Electron-Python</figcaption></figure><p>Using the Python library <a href="https://github.com/python-escpos/python-escpos">python-escpos</a> allows Print42 to support thermal printers (the kind you see in shops and supermarkets). A cheap, super fast thermal printer can thus be used as a “ticker tape” output for your log files. You might want to turn on Print42 expression filtering if your log files are verbose — or then again — thermal paper is cheap and requires no ink! Seriously, I believe that having a (instant on, silent when idle) thermal printer on each programmer’s desk is a productivity booster — not just for log files but for quickly printing all sorts of screen-grabs that can be written on and studied e.g. long expressions, complex code fragments etc. Sometimes you just need a pen and a few colours to think through a problem. I’m also a fan of fountain pens and inks — so that’s an organic vintage hobby I blend with my tech work.</p><p>Many Print42 features rely on web technologies. The infinite main scrolling display was implemented as &lt;div&gt; blocks. Font and image size options were naturally implemented in CSS, fancy search was implemented via the javascript plugin <a href="https://github.com/rhysd/electron-in-page-search">electron-in-page-search</a>.</p><p>Print42 supports printing selections of the tape to normal desktop printers too— though you won’t get the thermal paper “line by line and tear it off” vibe, because all desktop printers must of course print a page at a time.</p><h3>Electron Pros and Cons</h3><p>The ability to leverage my existing JavaScript, HTML, and CSS skills to build a UI has been priceless. I’m excited that I can build installable Python 3 ‘desktop apps’ for mac, windows and linux — that look like proper, professional apps including proper system menus and installers. There may be a few downsides, however.</p><p>I found that communicating between the Electron GUI and Python 3 using remote procedure calls is not ideal, however it’s pretty easy and on the bright side, arguably encourages clean partitioning of your app into UI vs business logic. Here is an example of Javascript (Electron) sending a UI preferences dictionary to Python for saving to a preferences file</p><pre><em>// Connect to Python subsystem<br></em>const zerorpc = require(&quot;zerorpc&quot;);<br>let client = new zerorpc.Client();<br>client.connect(&quot;tcp://127.0.0.1:PORTNUMBER&quot;);</pre><pre>function <em>py_save_prefs</em>() {<br>  let data = {<br>    magic: settings.PREFS_MAGIC,<br>    tape_file: settings.<em>get_VIRTUAL_TAPE_FILE</em>(),<br>    tape_file_gif: settings.<em>get_GIF_TAPE_FILE</em>(),<br>    auto_feed_delay: $(&#39;#auto_feed_delay&#39;).val(),<br>    auto_feed_enabled: $(&#39;#cb_auto_feed&#39;).prop(&#39;checked&#39;),<br>    print_to_epson_enabled: $(&#39;#cb_print_to_epson&#39;).prop(&#39;checked&#39;),<br>    font: $(&#39;#input-font&#39;).val(),<br>    file_history: settings.<em>get_file_history</em>()<br>  }<br>  client.invoke(&quot;save_prefs&quot;, data, (error, result) =&gt; {<br>    if (error)<br>      <em>show_error</em>(error)<br>    else {<br>      <em>// log.debug(&#39;preferences saved ok&#39;)<br>    </em>}<br>  })<br>}</pre><p><strong>Architecture Tip</strong>: I put all my Javascript functions that called out to Python e.g. like <em>py_save_prefs</em>() above, into a single Javascript file. I also clearly defined my Python ‘API’ in a single Python module. This way the communication between the two layers/sides was organised and neat.</p><p>There are <a href="https://www.reddit.com/r/Python/comments/9hmnnj/i_used_electron_python_to_build_a_visual_log/?">those</a> who don’t like the idea of using Electron at all. If you don’t have the web skills, then clearly the heavy use of HTML, CSS and Javascript required for using Electron, is not for you. Another reason against Electron may be that the deployed app is big because it bundles inside of itself a complete copy of the powerful cutting edge Chrome browser. A deployed app might be around 70Meg which expands to 200M on disk when installed. Note that the users of your app don’t need to have Chrome installed — Electron’s Chromium is self contained and secretly hiding inside your deployed app.</p><h3>Let’s get started</h3><p>The basic instructions and template project are available on the <a href="https://github.com/fyears/electron-python-example">electron-python github page</a></p><p><a href="https://github.com/fyears/electron-python-example">fyears/electron-python-example</a></p><p>The basic idea is that whilst any Electron app can run happily on its own and do lots of things inside Chromium — you add a simple bit of Javascript code to spawn Python (which acts as a server on a port) and Javascript talks to Python over that same port. The Python ‘server’ side of things is implemented something like:</p><pre># Python code</pre><pre>import zerorpc<br>import gevent, signal</pre><pre>port = 1234<br>addr = <strong>&#39;</strong>tcp://127.0.0.1:<strong>&#39; </strong>+ port<br>s = zerorpc.Server(<strong>PythermalApi</strong>())<br>s.bind(addr)</pre><pre>gevent.signal(signal.SIGTERM, s.stop)<br>gevent.signal(signal.SIGINT, s.stop)  <em># ^C<br><br></em>s.run()</pre><p>The call to s.run() blocks and voila we have a server that processes incoming API calls.</p><p>The class PythermalApi() above, specifies the API that I am exposing — a Python class whose methods end up being the API endpoints. Simple! The Python API is thus my ‘business logic’:</p><pre># Python code</pre><pre>class PythermalApi(object):</pre><pre>    def <strong>echo</strong>(self, text):<br>        <em>&quot;&quot;&quot;echo any text&quot;&quot;&quot;<br>        </em>return text</pre><pre>    .... (more endpoints) ...</pre><p>For example, the Python API function echo is now a function that Electron/Javascript can call with the following Javascript code:</p><pre>// Javascript code</pre><pre>client.invoke(&quot;echo&quot;, &quot;hello&quot;, (error, result) =&gt; {<br>    if (error)<br>      <em>show_error</em>(error)<br>    else {<br>        <em>console</em>.log(&#39;Got this from Python: &#39; + result);<br><em>    </em>}<br>  })</pre><p>In this example Python API endpoint echo is simply returning the text that Javascript sends as a parameter, back to Javascript. You can pass numbers, dictionaries, lists etc. as parameters and as return values.</p><h3>Installation</h3><p>The Python side of things involves installing <a href="http://www.zerorpc.io/">zerorpc</a>,</p><blockquote>An easy to use, intuitive, and cross-language RPC</blockquote><blockquote>zerorpc is a light-weight, reliable and language-agnostic library for distributed communication between server-side processes. It builds on top of <a href="http://www.zeromq.org/">ZeroMQ</a> and <a href="http://msgpack.org/">MessagePack</a>. Support for streamed responses — similar to python generators — makes zerorpc more than a typical RPC engine. Built-in heartbeats and timeouts detect and recover from failed requests. Introspective capabilities, first-class exceptions and the command-line utility make debugging easy.</blockquote><p>which is the mechanism by which nodejs calls functions in Python. Here is my final Print42 <strong>Pipfile</strong></p><pre>[[source]]<br>url = &quot;https://pypi.python.org/simple&quot;<br>verify_ssl = true<br>name = &quot;pypi&quot;</pre><pre>[packages]<br>zerorpc = &quot;*&quot;<br>python-escpos = &quot;==3.0a4&quot;<br>attrs = &quot;*&quot;<br>pyusb = &quot;*&quot;<br>click = &quot;*&quot;<br>gevent = &quot;*&quot;<br>appdirs = &quot;*&quot;<br>pillow = &quot;&lt;5.1.0&quot;<br>cffi = &quot;*&quot;<br>greenlet = &quot;*&quot;</pre><pre>[dev-packages]<br>PyInstaller = &quot;*&quot;<br>pywin32 = {version = &quot;*&quot;, sys_platform = &quot;== &#39;win32&#39;&quot;}</pre><pre>[requires]<br>python_version = &quot;3.6&quot;</pre><pre>[pipenv]<br>allow_prereleases = true</pre><p>Pipfiles are an alternative to requirements.txt and virtualenv environments. You can install needed dependencies with the command <strong>pipenv install</strong>, then activate the virtual environment with the command <strong>pipenv shell</strong>. Read more about the fabulous pipenv <a href="https://pipenv.readthedocs.io/en/latest/">here</a>. I’m a big fan.</p><p>The nodejs/Electron side of things involves git cloning the sample project, running <strong>npm install</strong> (assuming you have installed nodejs) and then typing <strong>npm start</strong> to launch the resulting app.</p><p>Alternatively, (my preference), you can build an Electron project from scratch using something like modern and current like <a href="https://electronforge.io/">electron-forge</a> and simply paste in the fragments of code (from the fyears template project) needed to perform the communication with Python.</p><p>The equivalent to Python’s Pipfile/requirements.txt in Electron/nodejs is the file package.json<strong>. </strong>Here is my final Print42 <strong>package.json</strong></p><pre>{<br>  &quot;name&quot;: &quot;print42&quot;,<br>  &quot;productName&quot;: &quot;Print42&quot;,<br>  &quot;version&quot;: &quot;1.0.2&quot;,<br>  &quot;description&quot;: &quot;Ticker tape and scrapbook for tailing logfiles, thermal printer support&quot;,<br>  &quot;main&quot;: &quot;src/index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;electron-forge start&quot;,<br>    &quot;package&quot;: &quot;electron-forge package&quot;,<br>    &quot;make&quot;: &quot;electron-forge make&quot;,<br>    &quot;publish&quot;: &quot;electron-forge publish&quot;,<br>    &quot;lint&quot;: &quot;eslint src --color&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;Andy&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;config&quot;: {<br>    &quot;forge&quot;: {<br>      &quot;make_targets&quot;: {<br>        &quot;win32&quot;: [<br>          &quot;squirrel&quot;<br>        ],<br>        &quot;darwin&quot;: [<br>          &quot;zip&quot;,<br>          &quot;dmg&quot;<br>        ],<br>        &quot;linux&quot;: [<br>          &quot;deb&quot;,<br>          &quot;rpm&quot;<br>        ]<br>      },<br>      &quot;electronPackagerConfig&quot;: {<br>        &quot;packageManager&quot;: &quot;npm&quot;,<br>        &quot;prune&quot;: true,<br>        &quot;icon&quot;: &quot;src/icons/icon&quot;,<br>        &quot;ignore&quot;: [<br>          &quot;/src/pycalc$&quot;,<br>          &quot;\\.git(ignore|config)&quot;,<br>          &quot;\\.vscode&quot;,<br>          &quot;\\.idea&quot;,<br>          &quot;/package-lock\\.json&quot;,<br>          &quot;Pipfile($|\\.lock)&quot;,<br>          &quot;/(api_pythermal|api|prtail)\\.spec&quot;,<br>          &quot;/bin$&quot;,<br>          &quot;/build$&quot;,<br>          &quot;/out2$&quot;,<br>          &quot;/Output$&quot;,<br>          &quot;/README\\.md&quot;,<br>          &quot;/print42\\.iss&quot;,<br>          &quot;/UsbDk_1.0.19_x64\\.msi&quot;,<br>          &quot;/(api_pythermal|t|t2)\\.py$&quot;,<br>          &quot;/pythermal$&quot;<br>        ]<br>      },<br>      &quot;electronInstallerDMG&quot;: {<br>        &quot;title&quot;: &quot;Print42 Install&quot;,<br>        &quot;icon&quot;: &quot;src/icons/icon.icns&quot;<br>      },<br>      &quot;electronWinstallerConfig&quot;: {<br>        &quot;name&quot;: &quot;print42&quot;<br>      },<br>      &quot;electronInstallerDebian&quot;: {},<br>      &quot;electronInstallerRedhat&quot;: {},<br>      &quot;github_repository&quot;: {<br>        &quot;owner&quot;: &quot;&quot;,<br>        &quot;name&quot;: &quot;&quot;<br>      },<br>      &quot;windowsStoreConfig&quot;: {<br>        &quot;packageName&quot;: &quot;&quot;,<br>        &quot;name&quot;: &quot;print42&quot;<br>      }<br>    }<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;always-tail&quot;: &quot;^0.2.0&quot;,<br>    &quot;electron-compile&quot;: &quot;^6.4.2&quot;,<br>    &quot;electron-in-page-search&quot;: &quot;^1.3.2&quot;,<br>    &quot;electron-log&quot;: &quot;^2.2.14&quot;,<br>    &quot;electron-squirrel-startup&quot;: &quot;^1.0.0&quot;,<br>    &quot;file-url&quot;: &quot;^2.0.2&quot;,<br>    &quot;fix-path&quot;: &quot;^2.1.0&quot;,<br>    &quot;jimp&quot;: &quot;^0.2.28&quot;,<br>    &quot;shelljs&quot;: &quot;^0.8.2&quot;,<br>    &quot;tmp&quot;: &quot;0.0.33&quot;,<br>    &quot;zerorpc&quot;: &quot;git+https://github.com/fyears/zerorpc-node.git&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;babel-plugin-transform-async-to-generator&quot;: &quot;^6.24.1&quot;,<br>    &quot;babel-preset-env&quot;: &quot;^1.6.1&quot;,<br>    &quot;babel-preset-react&quot;: &quot;^6.24.1&quot;,<br>    &quot;electron-forge&quot;: &quot;^5.1.1&quot;,<br>    &quot;electron-prebuilt-compile&quot;: &quot;1.8.4&quot;,<br>    &quot;electron-rebuild&quot;: &quot;^1.7.3&quot;,<br>    &quot;eslint&quot;: &quot;^3.19.0&quot;,<br>    &quot;eslint-config-airbnb&quot;: &quot;^15.1.0&quot;,<br>    &quot;eslint-plugin-import&quot;: &quot;^2.9.0&quot;,<br>    &quot;eslint-plugin-jsx-a11y&quot;: &quot;^5.1.1&quot;,<br>    &quot;eslint-plugin-react&quot;: &quot;^7.7.0&quot;,<br>    &quot;semver&quot;: &quot;^5.5.0&quot;<br>  }<br>}</pre><p>Note that you would typically let e.g. the electron-forge command build thepackage.json file for you, and then you would add what you need later e.g. install additional nodejs packages with npm install PACKAGENAME --saveas well as adding additional lines manually using an editor (ummm… Visual Code or PyCharm first, Vim second :)</p><p><strong>Dec 2019 Update:</strong> The electron-forge configuration inside your package.json’s “config”: { “forge”: … has changed recently. For example you need to rename electronPackagerConfig topackagerConfig see my <a href="http://bit.ly/electron-forge-migration">quick migration guide</a>.</p><p>Here is my December 2019 version of my Print42 package.json which includes the latest electron-forge config format changes, an electron 3 reference (don’t use higher electrons till zerorpc library is updated), and the reference to the <a href="https://github.com/0rpc/zerorpc-node">official zerorpc nodejs library</a>. It now also contains a section for building an .deb installer since I now support Print42 on Linux (Ubuntu and Raspberry Pi) — you can double click on a .deb file and it will install in Ubuntu. I built on Ubuntu 18.04 and was able to install and uninstall Print42 on Ubuntu 18.04 and 19.10 OK.</p><pre>{<br>  &quot;name&quot;: &quot;print42&quot;,<br>  &quot;productName&quot;: &quot;Print42&quot;,<br>  &quot;version&quot;: &quot;1.0.4&quot;,<br>  &quot;description&quot;: &quot;Log and Print to modern Thermal printers&quot;,<br>  &quot;main&quot;: &quot;src/index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;electron-forge start&quot;,<br>    &quot;reportandy&quot;: &quot;electron src/indexreportandy.js&quot;,<br>    &quot;package&quot;: &quot;electron-forge package&quot;,<br>    &quot;make&quot;: &quot;electron-forge make&quot;,<br>    &quot;publish&quot;: &quot;electron-forge publish&quot;,<br>    &quot;lint&quot;: &quot;eslint src --color&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;Andy&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;config&quot;: {<br>    &quot;forge&quot;: {<br>      &quot;makers&quot;: [<br>        {<br>          &quot;name&quot;: &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-squirrel&quot;,<br>          &quot;config&quot;: {<br>            &quot;name&quot;: &quot;print42&quot;<br>          }<br>        },<br>        {<br>          &quot;name&quot;: &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-zip&quot;,<br>          &quot;platforms&quot;: [<br>            &quot;darwin&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-dmg&quot;,<br>          &quot;config&quot;: {<br>            &quot;background&quot;: &quot;src/images/print42-dmg-bgnd.png&quot;<br>          },<br>          &quot;platforms&quot;: [<br>            &quot;darwin&quot;<br>          ]<br>        },<br>        {<br>          &quot;name&quot;: &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-deb&quot;,<br>          &quot;config&quot;: {<br>            &quot;icon&quot;: &quot;src/images/png/128x128.png&quot;<br>          },<br>          &quot;platforms&quot;: [<br>            &quot;linux&quot;<br>          ]<br>        }<br>      ],<br>      &quot;packagerConfig&quot;: {<br>        &quot;executableName&quot;: &quot;print42&quot;,<br>        &quot;packageManager&quot;: &quot;npm&quot;,<br>        &quot;prune&quot;: true,<br>        &quot;icon&quot;: &quot;src/icons/icon&quot;,<br>        &quot;ignore&quot;: [<br>          &quot;/src/pycalc$&quot;,<br>          &quot;\\.git(ignore|config)&quot;,<br>          &quot;\\.vscode&quot;,<br>          &quot;\\.idea&quot;,<br>          &quot;/package-lock\\.json&quot;,<br>          &quot;Pipfile($|\\.lock)&quot;,<br>          &quot;/(api_pythermal|api|prtail)\\.spec&quot;,<br>          &quot;/bin$&quot;,<br>          &quot;/build$&quot;,<br>          &quot;/out2$&quot;,<br>          &quot;/Output$&quot;,<br>          &quot;/README\\.md&quot;,<br>          &quot;/junk*&quot;,<br>          &quot;/print42\\.iss&quot;,<br>          &quot;/UsbDk_1.0.19_x64\\.msi&quot;,<br>          &quot;/(api_pythermal|t|t2)\\.py$&quot;,<br>          &quot;/pythermal$&quot;<br>        ]<br>      }<br>    }<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;always-tail&quot;: &quot;^0.2.0&quot;,<br>    &quot;electron-compile&quot;: &quot;^6.4.4&quot;,<br>    &quot;electron-in-page-search&quot;: &quot;^1.3.2&quot;,<br>    &quot;electron-log&quot;: &quot;^4.0.0&quot;,<br>    &quot;electron-squirrel-startup&quot;: &quot;^1.0.0&quot;,<br>    &quot;file-url&quot;: &quot;^3.0.0&quot;,<br>    &quot;fix-path&quot;: &quot;^2.1.0&quot;,<br>    &quot;jimp&quot;: &quot;^0.9.3&quot;,<br>    &quot;shelljs&quot;: &quot;^0.8.3&quot;,<br>    &quot;tmp&quot;: &quot;^0.1.0&quot;,<br>    &quot;zerorpc&quot;: &quot;^0.9.8&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;<a href="http://twitter.com/electron">@electron</a>-forge/cli&quot;: &quot;^6.0.0-beta.46&quot;,<br>    &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-deb&quot;: &quot;^6.0.0-beta.46&quot;,<br>    &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-dmg&quot;: &quot;^6.0.0-beta.46&quot;,<br>    &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-rpm&quot;: &quot;^6.0.0-beta.46&quot;,<br>    &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-squirrel&quot;: &quot;^6.0.0-beta.46&quot;,<br>    &quot;<a href="http://twitter.com/electron">@electron</a>-forge/maker-zip&quot;: &quot;^6.0.0-beta.46&quot;,<br>    &quot;babel-plugin-transform-async-to-generator&quot;: &quot;^6.24.1&quot;,<br>    &quot;babel-preset-env&quot;: &quot;^1.6.1&quot;,<br>    &quot;babel-preset-react&quot;: &quot;^6.24.1&quot;,<br>    <strong>&quot;electron&quot;: &quot;3&quot;,</strong><br>    &quot;electron-rebuild&quot;: &quot;^1.8.8&quot;,<br>    &quot;eslint&quot;: &quot;^3.19.0&quot;,<br>    &quot;eslint-config-airbnb&quot;: &quot;^15.1.0&quot;,<br>    &quot;eslint-plugin-import&quot;: &quot;^2.9.0&quot;,<br>    &quot;eslint-plugin-jsx-a11y&quot;: &quot;^5.1.1&quot;,<br>    &quot;eslint-plugin-react&quot;: &quot;^7.7.0&quot;,<br>    &quot;semver&quot;: &quot;^5.5.0&quot;<br>  }<br>}</pre><h3>Issues I had</h3><p>My first problem was wanting to install a later version of nodejs than the one being referred to on the electron-python github page. Secondly the advice to constantly clear node and electron caches during installation sounded a bit hacky.</p><p>So I decided to build the nodejs project from first principles, using <a href="https://electronforge.io/">electron-forge</a> e.g. npx create-electron-app my-app. This gave me the latest and greatest nodejs and electron. To make the version of nodejs you have compatible with the version of electron you have (which weirdly comes with its own version of node internally) you <strong>must</strong> run:</p><pre><em>#every time you run &#39;npm install&#39;,you have to run this:</em></pre><pre>./node_modules/.bin/electron-rebuild</pre><pre># or simply</pre><pre>$(npm bin)/electron-rebuild</pre><p>otherwise you will get ‘module mismatch’ errors when running npm install. You can always remove your ./node_modulesdirectory entirely and rebuild it with npm install if you ever get into bother. <strong>Dec 2019 Update: </strong>You currently must downgrade your electron version to electron 3 (see instructions below) to make the electron-rebuild step work with zerorpc. This may be fixed in the future.</p><p>My second problem was a hesitancy to use the special version of nodejs package zerorpc which the <a href="https://github.com/fyears/electron-python-example">sample fyears github project</a> specifies. After much research and gnashing of teeth, I gave in. It turns out that fyear has merely made a couple of lines of changes to the official zerorpc nodejs package, in order for it to, as he says, “use the optimized versions of msgpack and zeromq that don’t need c++ compilers for installing” ̶c̶o̶m̶p̶a̶t̶i̶b̶l̶e̶ ̶w̶i̶t̶h̶ ̶b̶e̶i̶n̶g̶ ̶a̶b̶l̶e̶ ̶t̶o̶ ̶p̶a̶c̶k̶a̶g̶e̶ ̶y̶o̶u̶r̶ ̶a̶p̶p̶ ̶i̶n̶t̶o̶ ̶a̶ ̶s̶i̶n̶g̶l̶e̶ ̶.̶e̶x̶e̶ ̶o̶r̶ ̶.̶a̶p̶p̶.̶ ̶T̶h̶e̶ ̶f̶o̶r̶k̶e̶d̶ ̶z̶e̶r̶o̶r̶p̶c̶ ̶r̶e̶p̶o̶ ̶i̶s̶ ̶b̶r̶a̶n̶c̶h̶e̶d̶ ̶o̶f̶f̶ ̶t̶h̶e̶ ̶o̶f̶f̶i̶c̶i̶a̶l̶ ̶r̶e̶p̶o̶ ̶s̶o̶ ̶a̶n̶y̶ ̶f̶u̶t̶u̶r̶e̶ ̶c̶h̶a̶n̶g̶e̶s̶ ̶s̶h̶o̶u̶l̶d̶ ̶r̶i̶p̶p̶l̶e̶ ̶t̶h̶r̶o̶u̶g̶h̶,̶ ̶s̶o̶ ̶a̶l̶l̶ ̶g̶o̶o̶d̶.̶</p><pre>̶e̶x̶t̶r̶a̶c̶t̶ ̶f̶r̶o̶m̶ ̶p̶a̶c̶k̶a̶g̶e̶.̶j̶s̶o̶n̶.̶.̶.̶<br>̶&quot;̶d̶e̶p̶e̶n̶d̶e̶n̶c̶i̶e̶s̶&quot;̶:̶ ̶{̶<br>̶&quot;̶z̶e̶r̶o̶r̶p̶c̶&quot;̶:̶ ̶&quot;̶^̶0̶.̶9̶.̶7̶&quot;̶ ̶ ̶&lt;̶-̶ ̶u̶s̶e̶ ̶t̶h̶e̶ ̶o̶f̶f̶i̶c̶i̶a̶l̶ ̶r̶e̶p̶o̶ ̶i̶f̶ ̶d̶o̶n̶&#39;̶t̶ ̶c̶a̶r̶e̶ ̶a̶b̶o̶u̶t̶ ̶p̶a̶c̶k̶a̶g̶i̶n̶g̶<br>̶&quot;̶z̶e̶r̶o̶r̶p̶c̶&quot;̶:̶ ̶&quot;̶g̶i̶t̶+̶h̶t̶t̶p̶s̶:̶/̶/̶g̶i̶t̶h̶u̶b̶.̶c̶o̶m̶/̶f̶y̶e̶a̶r̶s̶/̶z̶e̶r̶o̶r̶p̶c̶-̶n̶o̶d̶e̶.̶g̶i̶t̶&quot;̶ ̶ ̶&lt;̶-̶ ̶u̶s̶e̶ ̶t̶h̶i̶s̶ ̶c̶u̶s̶t̶o̶m̶ ̶r̶e̶p̶o̶ ̶i̶f̶ ̶y̶o̶u̶ ̶w̶a̶n̶t̶ ̶t̶o̶ ̶p̶a̶c̶k̶a̶g̶e̶<br>̶}̶</pre><p><strong>Dec 2019 Update: </strong>Since fyears has <a href="https://github.com/fyears/electron-python-example/issues/22">recently deleted</a> his zerorpc repository you might as well just use the official zerorpc repository — simply npm install zerorpc — save. Remember to $(npm bin)/electron-rebuild every time you use npm so that native packages are rebuilt for the internal version of node that electron uses. If you get an error during the rebuild, its probably because zerorpc v 0.9.8 is <a href="https://github.com/0rpc/zerorpc-node/issues/108">not yet compatible with later version of electron</a>, so you will have to <a href="https://github.com/electron/electron-rebuild/issues/343">stick to electron 3</a> by editing package.json and changing &quot;electron&quot;: &quot;7.1.5&quot;, to &quot;electron&quot;: &quot;3&quot;, then rm -rf node_modules, npm install. Now running $(npm bin)/electron-rebuild succeeds.</p><p>Note: also that, on a mac,brew install zeromq is not needed, because installing zerorpc via python’s pip install zerorpc or pipenv install zerorpc<strong> </strong>is enough, and gives you the relevant libraries and the zerorpc CLI.</p><p>I develop under Mac OS, but I managed to get my project running fine under Windows 10. I used the windows equivalent to brew which is the program <a href="https://chocolatey.org/">chocolaty</a> to install a bash shell containing git e.g. choco install git — or you can simply use the <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">linux subsystem for windows</a> to get your bash shell under Windows and your git tooling.</p><h3>Packaging</h3><p>Packaging is a three step process.</p><ul><li>Step 1: First you run pyinstaller to bundle up all the Python files and create a standalone Python executable in the dist directory. When this exe is run by Electron, the Python app runs as a zerorpc server on a particular port. You will need to create a .spec file to keep your pyinstaller configuration in (see example below).</li><li>Step 2: Then you run nodejs electron-packager which does the same bundling for electron <strong>plus</strong> grabs the python dist directory (created by the previous step, plus any other directories that you don’t exclude) and creates a distributable .app for Mac and .exe for Windows. It optionally creates .dmg files for Mac. If you created your electron project with electron-forge then the appropriate commands are electron-forge packageand electron-forge make. <br><strong>Dec 2019 update:</strong> Note thatelectron-forge won’t be available as a CLI command unless it is installed globally with npm’s -g parameter so you will have to run node_modules/.bin/electron-forge to invoke it. Since the <a href="https://www.electronforge.io/">recommended bootstrap</a> for an electron-forge project is npx create-electron-app my-app you won’t get such a global install but you will get a package.json which includes scripts (which are like aliases to run certain command via npm run scriptname and which you can edit, change and add your own) so that you can simply invokenpm run package and npm run make which are even easier ways to invoke these commands. The package step builds a self contained dir, the make step builds a deployable (app, dmg, deb etc.)</li><li>Step 3 (optional): For Windows you will probably also want to make a proper installer/uninstaller. I use the free program <a href="http://jrsoftware.org/isinfo.php">Inno Setup</a> for this last step, under Windows.</li></ul><p>In step 2 (whole app creation), I recommend that you tellelectron-packager to exclude bits of your app that don’t need to be shipped, by adding entries in package.json under electronPackagerConfig / ignore. Be especially careful to exclude the pyinstaller build/ directory as it is huge and not needed in the deployed app. And of course you don’t want to ship your .git repository :-) You’ll notice the many entries for ignored/excluded files and directories in my package.json — here is the relevant section:</p><pre>&quot;ignore&quot;: [<br>          &quot;/src/pycalc$&quot;,<br>          &quot;\\.git(ignore|config)&quot;,<br>          &quot;\\.vscode&quot;,<br>          &quot;\\.idea&quot;,<br>          &quot;/package-lock\\.json&quot;,<br>          &quot;Pipfile($|\\.lock)&quot;,<br>          &quot;/(api_pythermal|api|prtail)\\.spec&quot;,<br>          &quot;/bin$&quot;,<br>          &quot;/build$&quot;,<br>          &quot;/out2$&quot;,<br>          &quot;/Output$&quot;,<br>          &quot;/README\\.md&quot;,<br>          &quot;/print42\\.iss&quot;,<br>          &quot;/UsbDk_1.0.19_x64\\.msi&quot;,<br>          &quot;/(api_pythermal|t|t2)\\.py$&quot;,<br>          &quot;/pythermal$&quot;<br>        ]</pre><h3>PyInstaller tips and tricks</h3><p>Step 1 (python standalone creation via <a href="https://www.pyinstaller.org/">pyinstaller</a>) can be tricky when needed libraries are not automatically detected, which is almost always the case. You need to figure out which library was missed and add it to the hiddenimports section of your .spec file. Conversely you will need to exclude big fat Python libraries that you don’t need to ship by adding entries to the excludes section.</p><p>And then even when packages are correctly included, some packages have auxiliary files that they depend on that are missed e.g. the file capabilities.json which contains a database of thermal printer protocols had to be explicitly included by some custom Python code I had to add (the .spec file actually just Python code). Here is my final Print42 .spec file</p><pre># -*- mode: python -*-<br><br>block_cipher = None<br><br>import sys<br>sys.modules[&#39;FixTk&#39;] = None<br><br>options = [ (&#39;v&#39;, None, &#39;OPTION&#39;), (&#39;W ignore&#39;, None, &#39;OPTION&#39;) ]<br><br>import os<br>import escpos<br><br># figure out path to file we need from a site package module<br>capabilities_json = os.path.join(os.path.dirname(escpos.__file__), &#39;capabilities.json&#39;)<br><br># Conditional trick<br>binaries_to_ship = [(&#39;libusb-1.0.dll&#39;, &#39;.&#39;)] if sys.platform == &#39;win32&#39; else []<br><br>a = Analysis([&#39;api_pythermal.py&#39;],<br>             pathex=[<br>                &#39;/Users/Andy/Devel/print42&#39;,<br>                &#39;c:\\Users\\Andy\\Desktop\\print42-win10&#39;<br>             ],<br>             binaries=binaries_to_ship,<br>             datas= [<br>                (capabilities_json, &#39;escpos&#39; ),<br>             ],<br>             hiddenimports=[<br>                &#39;escpos.constants&#39;,<br>                &#39;escpos.escpos&#39;,<br>                &#39;escpos.exceptions&#39;,<br>                &#39;escpos.printer&#39;,<br>                &#39;bottle_websocket&#39;,<br>                &#39;gevent.__ident&#39;,<br>                &#39;gevent._greenlet&#39;,<br>                &#39;gevent.libuv&#39;,<br>                &#39;gevent.libuv.loop&#39;,<br>                &#39;gevent.__semaphore&#39;,<br>                &#39;gevent.__hub_local&#39;,<br>                &#39;gevent.__greenlet_primitives&#39;,<br>                &#39;gevent.__waiter&#39;,<br>                &#39;gevent.__hub_primitives&#39;,<br>                &#39;gevent._event&#39;,<br>                &#39;gevent._queue&#39;,<br>                &#39;gevent.__imap&#39;,<br>                &#39;gevent._local&#39;,                <br>             ],<br>             hookspath=[],<br>             runtime_hooks=[],<br>             excludes=[&#39;tcl&#39;, &#39;tk&#39;, &#39;FixTk&#39;, &#39;_tkinter&#39;, &#39;tkinter&#39;, &#39;Tkinter&#39;, &#39;numpy&#39;,&#39;cryptography&#39;, &#39;django&#39;, &#39;PyQt5&#39;],<br>             win_no_prefer_redirects=False,<br>             win_private_assemblies=False,<br>             cipher=block_cipher)<br>pyz = PYZ(a.pure, a.zipped_data,<br>             cipher=block_cipher)<br>exe = EXE(pyz,<br>          a.scripts,<br>          exclude_binaries=True,<br>          name=&#39;api_pythermal&#39;,<br>          debug=False,<br>          strip=False,<br>          upx=True,<br>          console=True )<br>coll = COLLECT(exe,<br>               a.binaries,<br>               a.zipfiles,<br>               a.datas,<br>               strip=False,<br>               upx=True,<br>               name=&#39;api_pythermal&#39;)<br></pre><h3>Packaged/Deployment Directory Structures</h3><p>The trickiest bit is understanding what deployed files and directories are being created and how they all relate to each other. You may need to learn to explore inside .app files (on a Mac, r. click, show package contents) to do this.</p><p>The main trick to Electron finding and launching Python at runtime is a piece of Javascript that you must include in your electron app. The script caters for both a development situation and a situation when you are deployed on a user’s machine — the way of launching Python is slightly different in each case. This script is available at the fyears github Electron-Python site. <br><strong>Post build development workflow tip:</strong> The Javascript code which spawns Python relies on detecting the dist/ directory, so whilst developing it is good practice to delete the dist/ directory so that your app is run correctly in development mode.</p><p>Under Mac my build script was</p><pre>rm -rf build/<br>rm -rf dist/<br><br># Step 1. Python build - just includes .pyc not source code ok<br>pyinstaller api_pythermal.spec<br><br># Step 2. <br>electron-forge package<br><br># Run - test<br>./out/print42-darwin-x64/print42.app/Contents/MacOS/print42<br><br># Make the .dmg<br>npm run make</pre><p>On a Mac, note that electron-forge package (step 2) builds the .app — if you want a .dmg as well, you need to also run npm run make.</p><p>Under windows 10 my build script was</p><pre>if exist build rmdir /s build<br>if exist dist rmdir /s dist<br><br><em>REM Python build - just includes .pyc not source code ok<br></em>pyinstaller api_pythermal.spec<br><br><em>REM quick test of python side of things<br></em>dist\api_pythermal\api_pythermal.exe<br><br>npm run package</pre><pre><em>REM Run - test final application<br></em>echo The exe is built and lives in the &#39;out&#39; directory</pre><pre>out\Print42-win32-x64\Print42.exe<br><br>echo Next run inno script, result typically is Output/setup.exe</pre><p>Notice that after the pyinstaller step, I actually run dist\api_pythermal\api_pythermal.exe which runs the python app that, as explained earlier, is really a server waiting for incoming remote procedure calls from Electron/nodejs/Javascript. I run the Python executable to check that the pyinstaller step worked ok. As a bonus, I can also open a terminal and run client commands like:</p><pre>zerorpc tcp://localhost:4242 print &quot;this is a test&quot;<br>zerorpc tcp://localhost:4242 api_call22<br>zerorpc tcp://localhost:4242 add 1 1</pre><p>where print, api_call22 and add are all Python entry points. This is a great CLI based way to test the Python side of things, without the Electron GUI. Once satisfied, I press ^C and say yes to continue the build script running.</p><p>Just to be clear, the resulting file dist\api_pythermal\api_pythermal.exe is merely the Python server — its the resulting file out\Print42-win32-x64\Print42.exe that we really want — this is the final distributable, standalone application. When the latter exe runs, Electron runs, and <em>your</em> Javascript code running in Electron/nodejs in turn spawns/runs the python server and talks to it as necessary. When Electron dies, ensure you kill the Python server running secretly on your user’s machine.</p><h3>Using Virtual Machines for building</h3><p>I found that I had to create a virtual machine running the oldest Mac OS that I <a href="https://www.macworld.co.uk/how-to/mac-software/download-old-os-x-3629363/">could find</a>, Mavericks. Why? Because mac apps built in this manner on a particular version of Mac OS will only run on that version of Mac OS or later. So for the broadest compatibility, I had to build on old Mavericks in a virtual machine. Then the resulting app can run in Mavericks and higher: Yosemite, El Capitan, Sierra, High Sierra and Mojave (ooh I like Mojave dark theme and desktop stacks!)</p><p>I also used a virtual machine for my Windows 10 builds — though that is because I develop on a Mac, though I suspect the same issue haunts Windows 10 too. I nevertheless built with the latest Windows 10 — hopefully the forced updates to Windows 10 that get pushed down to users will keep your Electron-Python apps compatible with a wide user base.</p><h3>Conclusion</h3><p>The journey was quite long, but I feel quite chuffed that I managed to create a real, cross-platform, downloadable product with a nice GUI, in Python 3. And I trust this blog will help you to do this too.</p><p>Please give <a href="http://bit.ly/print42atug"><strong>Print42</strong></a> a try — it has been created as a tool to help developers. And someone <em>please</em> wrap Electron-Python into an IDE so that in the future all we have to do is click a ‘build’ button — like we could 20 years ago. :-)</p><h3>My Other Cool Software</h3><ul><li><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*v2ecMpZhMtQIudbiR_ssHQ.gif" /><figcaption><a href="https://www.gituml.com/">GitUML</a> — generate UML diagrams instantly from any GitHub repository containing Python code (web app). A revolution in documentation — diagrams automatically update when you push code using git</figcaption></figure><ul><li><a href="http://pynsource.com/">Pynsource</a> — UML for Python (desktop app)</li><li><a href="https://pyrpn.atug.com/">Python to RPN</a> — Run Python 3 on vintage HP calculators (web app)</li></ul><h3>About Andy Bulka</h3><ul><li>Main website and blog <a href="http://www.andypatterns.com/">www.andypatterns.com</a></li><li>Medium article: <a href="https://medium.com/@abulka/async-await-for-wxpython-c78c667e0872">Async/await for wxPython</a> — Python 3 GUI apps with asynchronous functionality.</li><li>Medium article: <a href="https://medium.com/@abulka/getting-python-and-wxpython-apps-into-the-ubuntu-app-store-ccca7ae537a3">Getting Python and wxPython apps into the Ubuntu app store</a></li><li>Github <a href="https://github.com/abulka?tab=repositories">https://github.com/abulka</a></li></ul><h3>Resources for Learning Electron</h3><ul><li><a href="http://electron.atom.io/docs">electron.atom.io/docs</a> — all of Electron’s documentation</li><li><a href="http://electron.atom.io/community/#boilerplates">electron.atom.io/community/#boilerplates</a> — sample starter apps created by the community</li><li><a href="https://github.com/electron/electron-quick-start">electron/electron-quick-start</a> — a very basic starter Electron app</li><li><a href="https://github.com/electron/simple-samples">electron/simple-samples</a> — small applications with ideas for taking them further</li><li><a href="https://github.com/electron/electron-api-demos">electron/electron-api-demos</a> — an Electron app that teaches you how to use Electron</li><li><a href="https://github.com/hokein/electron-sample-apps">hokein/electron-sample-apps</a> — small demo apps for the various Electron APIs</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e8c807bfa5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>