Saturday, March 15, 2008

Running the twisted deamon (twistd) on Windows

Twisted is a networking library for python, which I find really good. I've only just started playing with it, and ran into some problems when trying to get it to run as a daemon under windows (using twistd - the twisted daemonizer). The information about this on the web seemed scarce, so I decided to post my findings.

When you install twisted, it comes with a special command-shell. But after looking at it, I found that it wasn't all that special afterall. It's just a batch-script that sets up a regular shell for you, all ready to start twistd.

As I do my programming in Eclipse, I wanted to start the server directly from inside the IDE. The way I did this, was by adding a .bat file to my project. The contents of the .bat file needs to be something like this:

set PATH=%PATH%;c:\python25;c:\python25\scripts
set PATHEXT=%PATHEXT%;.py;.pyc;.pyw;.pyo
set PYTHONPATH=%PYTHONPATH%;c:\your_source_dir
cd c:\your_source_dir
twistd -noy your_server_daemon.tac
pause

You have to change three things here, the two your_source_dir and your_server_daemon.tac and also the python directory.

The first line adds the python executable to your path. In my case this is c:\python25 - you will need to change this depending on your python install. It also adds the scripts directory where your twistd.py should reside.

Next we set the PATHEXT variable, this lets you run .py files (and .pyc and so on) directly from the command line without invoking the python interpreter manually (the way it works on *nix).

After that, we add the directory (or directories) where our source files reside to the PYTHONPATH. Without this, you will get an "ImportError: No module named blabla", or "Failed to load application: No module named blabla" for all your imports. (You can also add to the pythonpath from inside your program, but I find that it's a bit cleaner this way).

Next we change into our source directory, simple as that.

After that, it's simply a matter of starting the twisted daemon (twistd) with our configuration (.tac) file. -noy means that we start the specified .tac and log to stdout (look up twistd in the twisted docs for more info). To stop the server, simply press Ctrl+C.

The pause at the end is only there so that the window doesn't close immediately after the program ends, but waits for a keypress.

More on twisted here:

No comments: