Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Friday, January 22, 2010

Running Python's Distutil Created Wininst Installers (.exe) from the Commmand Line

I recently created an installer with Inno Setup that was used to launch a bunch of other installers. As such, I needed to, more or less, run those sub-installers from the command line during install and uninstall. The sub-installers were executables generated by Python's distutils using the wininst bdist command (i.e. "wininst" installers for Windows).

Given the wininst installer mypymodule.1.2.exe, to install, execute the command mypymodule.1.2.exe. This places the files Removemypymodule.exe and wininst-mypymodule.log in the root directory of the Python installation. To uninstall execute the command path/to/python/root/Removemypymodule.exe -u path/to/python/root/wininst-mypymodule.log.

Sunday, October 18, 2009

Deploying a Django Application on Apache WSGI on Windows

Following are some notes I made during my last install of a Django based web application on an Apache web server running on Windows.

This assumes a Django application is being installed on a computer with no prior Django installs. I also describe a particular example, but the same steps can be applied to many applications, just replace my application specifics with your application specifics.

  • Install Python 2.6.
    • Run the MSI installer and install in C:\Programs.
    • Create the following environment variable: PYTHON_HOME=C:\Programs\Python26 (see System Properties/Advanced/Environment Variables).
    • Append the newly created variable to your PATH variable. Also append %PYTHON_HOME%\Scripts and %PYTHON_HOME%\Lib
    • Open a command line prompt, execute the command python. This should start the Python interactive interpreter.
  • Install Django 1.1.
    • Unpack the distribution (usually a tar.gz or .zip file) in some temporary directory. You might need to install (the free and excellent) 7-Zip for this.
    • Open a command line prompt in the directory Django was unpacked in, most likely Django-1.1.
    • Execute python setup.py install (or setup.py install).
    • To check if the install went correctly, you should be able to import the Django module in Python. Start Python from the command line, and execute:
        import django
        django.VERSION
                
  • Install Apache 2.2.
    • Runs the Windows MSI installer provided from the Apache web site.
    • From a web browser, enter the URL http://localhost. A valid web page hosted be Apache should be displayed.
  • Install the modwsgi module.
    • The module file will be named something like mod_wsgi-win32-ap22py26-2.6.so (http://code.google.com/p/modwsgi/downloads/list).
    • Copy it to the modules directory of the Apache installation. E.g., C:/Program Files/Apache Software Foundation/Apache2.2/modules.
    • Rename it to mod_wsgi.so.
    • Open Apache's http.conf file.
      • Add the line LoadModule wsgi_module modules/mod_wsgi.so before all the other LoadModule entries.
      • Configure Apache for your Django project by adding the following to end of http.conf:
        # Static content
        
        Alias /media/ C:/Programs/TestDjango/mysite/media/
        
        <Directory C:/Programs/TestDjango/mysite/media/>
        Order deny,allow
        Allow from all
        </Directory>
        
        # Django dynamic content
        
        WSGIScriptAlias / C:/Programs/TestDjango/mysite/apache/django.wsgi
        
        <Directory C:/Programs/TestDjango/mysite/apache>
        Order deny,allow
        Allow from all
        </Directory>
        

        Where TestDjango is the Django project root. The paths below TestDjango will be specific to your project. This configuration serves all static media via the URL space /media/ and all the rest via WSGI and Django.

      • You may need to create the django.wsgi script if it's not already created. To do so, create a file django.wsgi and add the following to it:
            import os
            import sys
        
            sys.path.append('C:/Programs/TestDjango')
            os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
        
            import django.core.handlers.wsgi
            application = django.core.handlers.wsgi.WSGIHandler()
                      

        Note that sys.path.append('C:/Programs/TestDjango') is only needed if your project (TestDjango) is not on Python's path, PYTHONPATH.

    • Restart Apache. For this you can use the Apache Service Monitor from the taskbar tray.
    • From a web browser, attempt to hit the Django application's web page, such as http://localhost/mysite.

Sunday, September 13, 2009

PyDev: Workaround for the Undefined Class/Static Attribute Error

PyDev will incorrectly identify class (static) attributes as "undefined" if they are dynamically added to a class. Consider the following class:
class Quantity:
    def __init__(self, name, unit):
        self.name = name
        self.unit = unit

# Add some class/static attributes after class creation

Quantity.VOLTAGE = Quantity("Voltage", "volts")
Quantity.COUNTS = Quantity("Counts" , "counts")
Now, if we use a class attribute, such as VOLTAGE, PyDev will flag it with an "Undefined variable from import: VOLTAGE" error, even though it is valid.
print(Quantity.VOLTAGE) # <-- Flagged as an error
To work around this, add the annotation @DynamicAttrs to the class's docstring, as follows:
class Quantity:
    """ @DynamicAttrs """
    def __init__(self, name, unit):
        self.name = name
        self.unit = unit
Reference: Fabio on PyDev's user list.

Sunday, June 14, 2009

Links: reStructuredText for Python Documentation

Here are some links regarding reStructuredText used in Python docstrings (source code comments) and Sphinx, Python's new documentation system:

Sunday, May 31, 2009

Pyflakes Vim Script for Python Editing

I found another very useful Vim script for editing Python code: pyflakes.vim. It basically gives you on-the-fly code checking, similar to Eclipse: "pyflakes-vim shows wavy underlines underneath common Python errors like misspelling a variable name. It also warns about unused imports, redefined functions, etc.". It's not perfect in it's analysis, but it sure helps catch a lot of errors that normally don't get caught until runtime. I didn't follow the installation instructions since I generally load my file type scripts explicitly, and because I couldn't get the script to load using the instructions given. Instead I did the following:
  • Unzipped the contents of pyflakes-vim.zip to vimfiles/ftplugin
  • Added runtime ftplugin/pyflakes.vim to my vimfiles/ftplugin/python.vim script

Sunday, March 15, 2009

Curve Fitting and Plotting in Python: Two Simple Examples

Following are two examples of using Python for curve fitting and plotting. I'm using Python in a style that mimics Matlab -- although I could have used a pure object oriented style if I wanted, as the
matplotlib library for Python allows both.

Example 1: Linear Fit
import numpy
from matplotlib.pyplot import *

x = [-7.30000, -4.10000, -1.70000, -0.02564,
     1.50000, 4.50000, 9.10000]
y = [-0.80000, -0.50000, -0.20000, 0.00000,
     0.20000, 0.50000, 0.80000]

coefficients = numpy.polyfit(x, y, 1)
polynomial = numpy.poly1d(coefficients)
ys = polynomial(x)
print coefficients
print polynomial

plot(x, y, 'o')
plot(x, ys)
ylabel('y')
xlabel('x')
xlim(-10,10)
ylim(-1,1)
show()



y = 0.10160693 x - 0.02865838

Example 2: 6th Order Polynomial Fit
from numpy import *
from matplotlib.pyplot import *

x = [2.53240, 1.91110, 1.18430, 0.95784, 0.33158,
     -0.19506, -0.82144, -1.64770, -1.87450, -2.2010]

y = [-2.50400, -1.62600, -1.17600, -0.87400, -0.64900,
     -0.477000, -0.33400, -0.20600, -0.10100, -0.00600]

coefficients = polyfit(x, y, 6)
polynomial = poly1d(coefficients)
xs = arange(-2.2, 2.6, 0.1)
ys = polynomial(xs)

plot(x, y, 'o')
plot(xs, ys)
ylabel('y')
xlabel('x')
show()



y = -0.00412906x6 - 0.00160756x5 + 0.03629611x4 - 0.02020429x3 - 0.17468383x2 - 0.30660343x - 0.5139088

References
  1. Python
  2. matplotlib
  3. scipy/numpy

Wednesday, March 4, 2009

Vim Scripts I Use When Editing Python Source

Following are some public vim scripts I have found the most useful for editing python source files:

Wednesday, February 11, 2009

Compiling Vim (on Windows) To Use Different Python Versions

I recently wanted to use Python Omni Complete for Vim, but whenever I executed the complete command <c-x><c-o> it failed with the error:
Error: Required vim compiled with +python
E117: Unknown function: pythoncomplete#Complete
This is incorrect. After doing a :version command, Vim showed it was compiled for Python support (the +python/dyn option was present). The real problem was Vim could not find the correct version of Python it was expecting: I had 2.6 installed, Vim wanted 2.4 (DYNAMIC_PYTHON_DLL="python24.dll").

Following is one way to compile Vim to use a different version of Python than that shipped with Vim. I targeted 2.6, but the steps can be tweaked to work for any version of Python. It is assumed Vim and Python are already installed.
  1. Obtain a C++ compiler. I considered two, GCC from Cygwin and GCC from MinGW. I went with the latter simply because it was easy to install only the C/C++ development tools (e.g. GCC, make) that I needed. The Cygwin installer had far too many packages to chose from. I didn't want to waste my time determining what was necessary to install from packages I had no interest in.
  2. Obtain Vim source code and unzip somewhere, say C:\.
  3. Edit the MinGW make file. For me that is C:\vim\vim72\src\Make_ming.mak. Find the variable PYTHON_VER and set the version number to whatever version of Python you have installed. Also, find the variable PYTHON and set to the root of the Python installation directory. In my case,
    PYTHON=c:/Programs/Python26
    PYTHON_VER=26
    
  4. MinGW did not add the location of the GNU make tool to my PATH, so I had to manually do that next. Since I had no intentions of using this tool after I was done compiling Vim, I updated my path temporarily. To do that, I opened a command prompt in the directory of the make file (C:\vim\vim72\src) and executed
    set PATH=%PATH%;C:\Programs\MinGW\bin
    
    where C:\Programs\MinGW is the location where I installed MinGW.
  5. Compile GVim. Using the same command prompt window in which PATH was changed, execute
    mingw32-make -f Make_ming.mak gvim.exe
    
    Normally you would execute make -f Make_ming.mak gvim.exe, but make.exe seems to have been renamed to mingw32-make.exe in the MinGW installation.
  6. Install gvim.exe. After compiling is done, locate gvim.exe in the same directory as the make file (C:\vim\vim72\src) and copy to Vim's runtime directory. For my, C:\Program Files\Vim\vim72. There should already be a gvim.exe there.
  7. Make sure the Python 2.6 installation is on your path, namely the directory where Python26.dll is located.