Posts Tagged ‘ python

Create a single standalone .exe from a Python program

I have been working on a small command line tool that I wanted to distribute it as a single executable file on . I tried cx_freeze and py2exe. Both of these tools worked well, but I couldn’t find an easy way to compress make the whole program into a .exe file. py2exe and cx_freeze both create working programs, but there are always some dependent .zip archive or .dll’s somewhere that need to be distributed with it. Pyinstaller, I found, actually compresses everything into a single .exe. This makes a pretty big executable (my small command line utility created a 5MB .exe file), but it’s simple and it works.

To use pyinstaller:

  1. grab pyinstaller 1.5rc (1.4 doesn’t work with 2.7). extract the zip file anywhere.
  2. change directories to the pyinstaller folder you just created.
  3. Before you create your first executable, you will have to run this once.
  4. python .py
  5. Now, pyinstall needs to scan through your program and create what they call a spec file.
  6. python makespec.py --onefile path\to\program\program.py
  7. Now, run this command to generate the executable.
  8. python build.py program\program.spec

Once the command has finished, the standalone executable will be available in the program\dist folder inside of pyinstaller.
Instructions for how to do this for a linux executable on ubuntu linux can be found here: http://excid3.com/blog/2009/12/pyinstaller-a-simple-tutorial/. You can find more info on pyinstaller at their website: http://www.pyinstaller.org/.

View string including special characters like newlines in Python

After spending a frustrating hour or two trying to format a string, i stumbled on ’s repr() funcion. repr() allows you to inspect a string object when you’re troubleshooting your code. For example:

I was trying to understand a string that was shown in the terminal like this:

print mystring
Node - 192.168.1.104
ERROR:
Description = Generic failure

Seems pretty simple to remove the extra right? no. doing a string.replace(“\n”, ” “) did not fix it, but actually mangled the string. So here comes repr() to the rescue…

print repr(mystring)
'Node - 192.168.1.104\r\r\nERROR:\r\r\nDescription = Generic failure\r\r\n'

\r\r\n… i’ve never heard of it before, but knowing that it’s there, i could easily change my replace to:

print mystring.replace("\r\r\n", " ")
Node - 192.168.1.104 ERROR: Description = Generic failure