Making A Standalone Python App Mac

Last Updated on

We have successfully set up and installed a LAMP server on our Ubuntu machine, optimized our server, and now it’s time to learn how to write a Python application – our first one! We won’t be writing anything too fancy, but we will cover the basics of a Python application, and also talk a bit to either our MySQL or PostgreSQL database.

Throughout this tutorial, I will be using the nano editor in the terminal to write my Python code, but feel free to use whichever editor you please. It should not affect the outcome of this tutorial.

Also note that unlike many popular programming languages, Python uses whitespace indentation as a delimiter for code blocks, instead of the traditional curly braces or keywords. This allows Python to have extremely readable code, and forces you not to write single-line functions. Keep this in mind as you are writing your own program, as you don’t want to have issues caused by missing line breaks or indentation.

Formerly known as PyGTK, the Python GTK+ 3 project provides Python bindings to GTK objects (windows, widgets, and so on). GTK+ is most famously used as the foundation for the GNOME desktop, but it's available for stand-alone applications on Linux, Windows, and Mac. With Python GTK+ 3, the same framework is available for your Python projects.

How to Write a Python Application: Creating Our First .py File

Navigate to a folder that you would like to create your first Python file in, and create a file called test.py. Now open this file up in the editor and type the following code:

Save your file, and in the terminal, navigate to wherever you created this file, and run it by calling python test.py. You should see the correct output:

This is a very simple way to write a Python application and see the result. However, what if we want to run the application without typing python test.py every single time? To do that, we can add the following to our code:

That top line allows the file to locate the Python interpreter (which, by default, is in the /usr/bin/ folder). Save the file. Now we need to change the permission of this file so that it is executable by the terminal. Run the following:

Now we can run the program by simply typing:

Now, let’s add a variable to our program, as well as a conditional statement. What we want the variable to do is hold our first name (you’ll want to change the name used in this example to your own), and then our conditional statement will check to see whether the name is correct. If it is, the program will say hello. If it isn’t, the program will ask for the correct name.

Let’s run our program and see the output.

You should see something similar to the above. Now let’s edit our program and misspell the name to see whether our condition is really working:

Run the program again, and you should see:

Now we know that the conditional statement is checking the name, and if it’s different from the expected value, the program will ask for the correct name.

Writing a Simple Function

Let’s take our basic conditional statement and turn it into a function. We’ll write our function with a single argument that will be used to store our name. The program will then ask our user whether the name is correct, and the user can answer yes or no (inside of the terminal). Depending on whether the name is correct or incorrect, the program will display a different message.

You can define your function by using the def keyword, followed by a name for your function (in this example, it’s called “checkName”). Inside of our function, we declare a single argument, which allows us to input information into the function to be used. After that, we ask our user whether the name is correct, which can be accomplished by using the input method in Python.

Next, we write a conditional similar to the one above, checking to see whether the name entered is correct. If it is, we welcome the user. If it’s not, we apologize. The first line of the conditional has the biggest change, and that’s because we are checking what the user has typed in (via the checkName object) to see whether it was yes or no. We also force the user’s input to be lowercase, so that no matter how they type in “yes” (whether it’s yes, YES, yEs, or Yes), it will always be compared the same way.

At the end of our file, we are simply running the function we just created, and passing in our name as the parameter.

We should now be able to run our script and walk through both conditionals:

Let’s take our function a step further and allow our somebody to enter their name if it’s not the one the program expected. This will only take one additional line and one changed line.

All of our changes lie right after our else: statement. Instead of just apologizing to the user, we assign a new value to our name parameter, which will both apologize and capture the new name for our user. Afterwards, we welcome our new user.

Running the application should look something like:

Creating MySQL Tables and Accessing Them

Now that we’ve written a simple function and used variables, user input, and conditional statements, let’s connect to our MySQL database (installed previously) to store and retrieve information.

Best free mac video editing software 2015. Lightworks lets you export the content to a wide range of formats.Price: $24.99/Monthly#9.

Before we start writing any code, we need to ensure that a MySQL driver is installed on our machine. We’ll do this by running the following command:

However, before we add any Python code to actually interact with MySQL, we need to create a database table. Let’s run MySQL in our terminal (you will have to enter your root MySQL password afterward):

Now let’s create a database in MySQL named “python”:

Let’s ensure that we’re connected to our new database in the terminal:

Now let’s create a table called “users” with one field for an auto-incrementing ID and one field for a first name:

Your terminal should look similar to this:

Now that we have our database and tables, let’s set up our Python script so we can access and modify it.

Opening up test.py, we should add the following code to our file:

You can see that after we declare our Python path, we import the Python-MySQLdb tool that we installed earlier. This is necessary so our program can interact with our MySQL database. Our next line is creating an object named db that stores our connection to MySQL. Ensure that each field here uses your correct host, username, password, and database (although the only thing that should be changing on your end is the password).

Next, we create an object named cursor that allows us to actually execute queries in MySQL. After that, we use the cursor object we just created and run a MySQL command to insert a row into the users field. In this case, I’m inserting my first name into the firstname field. We then call db.commit() to ensure that all changes we make to our database are saved.

Now if we save our file and run the following command inside of MySQL in our terminal, we should see:

This means that we have successfully inserted a row into our users table in our database. We now know that our Python application is talking to MySQL.

Creating PostgreSQL Tables and Accessing Them

If we want to interact with a PostgreSQL (abbreviated throughout the article as “Postgres”) database, we will need to install and use a tool call psycopg2. We can do that by typing the following into the terminal:

We need to run Postgres inside of the terminal so that we can create and access our tables, but we need to create a Postgres user first. We’ll do that by first logging in as the default Postgres user:

Now let’s create a Postgres database named “python”:

Let’s ensure that we’re connected to our new database in the terminal:

We now need to create a new user and add them to the database so we can execute commands:

Now let’s create a table called “users” with one field for an auto-incrementing ID and one field for a first name:

Your terminal should look similar to this:

Now that we have our database and tables, let’s set up our Python script so we can access and modify it.

Opening up test.py, we should add the following code to our file:

You can see that after we declare our Python path, we import the Psycopg2 tool that we installed earlier. This is necessary so our program can interact with our Postgres database. Our next line is creating an object named db that stores our connection to Postgres. Ensure that each field here uses your correct host, username, password, and database (although the only thing that should be changing on your end is the password).

Next, we create an object named cursor that allows us to actually execute queries in Postgres. After that, we use the cursor object we just created and run a Postgres command to insert a row into the users field. In this case, I’m inserting my first name into the firstname field. We then call db.commit() to ensure that all changes we make to our database are saved.

Now if we save our file and run the following command inside of Postgres in our terminal, we should see:

This means that we have successfully inserted a row into our users table in our database. We now know that our Python application is talking to PostgreSQL.

The Finish Line

Congratulations, you now have a very simple Python application that is communicating with your database, storing variables, getting user input, and running conditional statements. You could further expand your program by asking the user their name and storing that in the database, and possibly adding more complexity to your database.

If you want to learn more about how to write a Python application, consider enrolling in a Nanodegree program, with hands-on projects, a flexible schedule, and career support. We offer Introduction to Programming which is great for beginners learning HTML, CSS, JavaScript, and Python. Or, check out the Python for Data Science Nanodegree program, also great for beginners!

GUI2exe

An excellent wxPython based graphical builder to the various Python executable builders. Available on Google Code, also see Mike Driscoll's blog for a tutorial on using GUI2exe with Py2exe

The McMillan Installer

The mcillian installer development is discontinued.

mirror: http://davidf.sjsoft.com/mirrors/mcmillan-inc/installer_dnld.html

Continued development(not tested yet): http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi

This works on Win32.
Unzip the Installer in a directory of your choice, and cd there.

Mac

Configure the Installer by running:

Python must be in your PATH for this to work, if it's not, type from the command prompt:

where c:python23 must be replaced with the root of your python installation.
Then, assuming the source code is app.py (placed in c:source):

Replace 'app' everywhere above with your application name.

You will end up with appapp.exe under the Installer dir.This is a one file .exe containing all the application.
If you don't want a one-file build, suppress the option --onefile above.
If you don't have upx installed (or don't want to use it), suppress the option --upx above.
The option --noconsole is needed to produce a windows gui application, instead of a console one (so the command shell won't pop up when you run the application).

[ More details to be written.. ]

py2exe

http://py2exe.sourceforge.net/

Create a setup.py script for using py2exe to generating the exe file. (The script to compile in this case is wxTail.py):

Sample of the win32 command for running py2exe:

If you use the unicode version of wxpython you have to manually include the file unicows.dll form your python installation directory. Otherwise the application will crash at least on Windows 98.

--GeraldKlix

[ More details to be written.. ]

Installer

To turn your binary and accompanying library files into a Windows installer you can use:

  • innosetup from http://www.jrsoftware.org/isinfo.php

  • NSIS from http://nsis.sourceforge.net/ (and HM-NSIS-Edit http://hmne.sourceforge.net/ for the wizard).

Issues

When using py2exe with pythoncom (or with wxPython's ActiveXWrapper which uses pythoncom) py2exe has trouble finding the code for the generated COM wrapper modules and you end up with import errors. Here is the solution, which was sent to the mail list by Clark C. Evans:

  • When pythonwin is called to create an Python binding for a COM component, it generates a new python class and puts this class in the gen_py directory (which magically appears). I believe the problem is that the py2exe program doesn't expand the Python path to include the deployment directory, otherwise this directory would be found.. To work-aroud this problem, simply use the makepy program to generate a python wrapper for the activeX component you have (for example, IE Explorer). Then, rename this module file to something more palatable (like ie.py). Then, instead of using 'ensure module' simply import the re-named file -- the imported module is the class module. For example, to make the IE ActiveX demo work..
    1. Generate ie.py using makepy using the '-o' option
    2. Replace the 'ensure module' stuff in the demo code with..
    No other changes seem to be necessary.

Another work-around if you run into issues running py2exe compiled programs with the ActiveXWrapper controls (specifically the PDF Window control in wxPython 2.8) is to add a typelibs entry to the options argument in your setup.py file. See the sample setup.py below for an example.

Basically the typelibs line ensures py2exe picks up the dynamically imported module in pdfwin.py that is included with the Windows wxPython distribution.

On Linux

Summary

A binary distribution of a Python/wxPython program on Linux has these advantages:

  • There is no need for the user to have Python, wxPython or any other extensions you use installed
  • The versions of Python, wxPython and extensions are the ones you ship, not any they may already have installed. That means you don't need to worry about users using different versions of the extensions with your software.

Prerequisites

cx_Freeze

cx_Freeze turns a Python script into a binary file and any referenced binary modules.

Download cx_Freeze I recommend getting the binary distribution. If you extract it in /opt, then it will end up installed in /opt/cx_Freeze-2.1/ (this location is assumed through the rest of this document).

Also note that while cx_Freeze is free software, you do need to abide by the license agreement on the same page.

chrpath

The wxPython shared libraries have some pathnames hardcoded into them (also known as an rpath). chrpath removes this hardcoded path for where other shared libraries are searched.

Download chrpath from http://freshmeat.net/projects/chrpath/ By default it installs in /usr/local/bin which should be on your path.

Making your binary distribution

Make an output directory

Create a clean directory for the resulting files. I make one named dist.

Run cxFreeze

Assuming the main entrypoint to your program is example.py, this is what you run:

Everything should end up in the dist subdirectory, and the main binary will be named dist/example

Run chrpath

You now need to remove hard coded path information from the wxPython and other shared libraries. I use this shell script:

Change into the dist subdirectory and run the script. It should fix at least wxPython.wxc.so, and same other wx-controls you may use (eg calendar).

Python Install Mac

Package it up

You can now just tar up the dist subdirectory. Users can place the contents anywhere they choose on the filesystem, and call the main executable for everything to work.

I normally put all the files in a subdirectory of /usr/lib (for example: /usr/lib/example-1.0 and then put a wrapper script in /usr/bin that execs the binary in /usr/lib/example-1.0.

On Mac

py2app

http://undefined.org/python/py2app.html

BundleBuilder.py

The Python included with Mac OS X contains a tool called BundleBuilder.py which lets you package Python scripts into '.app' bundles that can be distributed on computers even without Python installed. (Although OS X 10.3 contains a complete implementation of Python.) Documentation on this tool (including an example of a wxPython app building script) can be found here:

Hp scanner software

http://www.python.org/cgi-bin/moinmoin/BundleBuilder

The important part to note is that you must manually include the wxWindows dynamic libraries at this point. See the lines in the example script containing myapp.libs.append to see how to do so. Hopefully a more targeted and detailed tutorial will be forthcoming. =) In the meantime, please feel free to post your questions to either [email protected] or [email protected] .

Create Standalone Python App

Examples

BitPim

The bitpim project produces Windows and Linux binary installers that don't require the user to have Python or wxPython installed (or even have to know what they are!)

Code is available in http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/bitpim/bitpim/

Run Python On Mac

makedist.py does the actual build an invokes the various other tools. bitpim.iss is the innosetup file. p2econfig.py is the py2exe file.