Thursday, January 24, 2008

Make Java program work through the proxy

It is not surprising that not many users know how to make a Java program work through a domain proxy if there is no place to enter proxy settings. Just because they are not developers they do not know that it is enough to launch this program with the following command line:

java -Dhttp.proxyHost=192.168.1.1 -Dhttp.proxyPort=3128 -jar SoftWare.jar %*

This works for anonymous or domain proxies only, because there are no password settings. To work through password-authenticated proxy, you will have to setup additional local or personal proxy that uses user/pass settings to authenticate and pass traffic to upstream one. Unfortunately, I can't name any software for user/pass authentication because I've never had to work with this problem, but I know that at least Privoxy is capable to forward requests.

Wednesday, January 09, 2008

Compiling Python extension with GCC

In my previous post I've described how to make C code accessible from Python. I used Visual C++ compiler cl.exe to build an extension (or module) for Python. This follow-up shows how to compile the same extension for windows using GCC. I bet you already know what GCC is and that it is available from MinGW install as a result of install procedure described long ago.

Grab the source from the previous post - it won't change. Everything what is going to happen are just changes in .exe and its command line options. Saving source as farpython.c and starting GCC to compile it:

gcc farpython.c

As usual, this won't produce anything useful except errors.

farpython.c:14:20: Python.h: No such file or directory
farpython.c:18: error: syntax error before '*' token
farpython.c:19: error: syntax error before '*' token
...

Additional include search path is specified using -I option in GCC.

gcc -IE:\ENV\Python25\include farpython.c

A different picture, but the output is still grim.

D:\Temp/ccyOaaaa.o(.text+0x1c):farpython.c: undefined reference to `_imp__PyArg_ParseTuple'
D:\Temp/ccyOaaaa.o(.text+0x4c):farpython.c: undefined reference to `_imp__Py_BuildValue'
D:\Temp/ccyOaaaa.o(.text+0x88):farpython.c: undefined reference to `_imp__Py_InitModule4'
D:\Temp/ccyOaaaa.o(.text+0xbe):farpython.c: undefined reference to `_imp__Py_InitModule4'
E:/ENV/MSYS/mingw/bin/../lib/gcc/mingw32/3.4.2/../../../libmingw32.a(main.o)(.text+0x106):main.c: undefined reference to `
WinMain@16'
collect2: ld returned 1 exit status

Luckily these errors are not concerned with the code. They are from linker (ld) complaining it could not find library with binaries for functions defined in Python.h. The last one about undefined reference to WinMain is different though, but let's skip it until we deal with missing libraries. Python libraries are located at E:\ENV\Python25\libs and option to GCC is -L.

gcc -IE:\ENV\Python25\include -LE:\ENV\Python25\libs farpython.c

The output is still the same. The problem here is that linker doesn't know which specific library we need to link with to get binary bits for Python.h functions. cl.exe from Visual C++ was able to detect the correct library somehow, but for GCC we have to specify its name explicitly with -l option. Note that this option goes after a name of all compiled .c files. It is because params up to and including .c files are for compiler component and everything that goes after can be treated as linker's.

gcc -IE:\ENV\Python25\include -LE:\ENV\Python25\libs farpython.c -lpython25

Check the output.

E:/ENV/MSYS/mingw/bin/../lib/gcc/mingw32/3.4.2/../../../libmingw32.a(main.o)(.text+0x106):main.c: undefined reference to `
WinMain@16'
collect2: ld returned 1 exit status

WinMain is an entrypoint or starting point of any program on windows platform, but Python extension is not a program that starts execution itself. .pyd is a .dll, or shared library with functions to be called by other programs. To tell that to GCC we add -shared switch to command line.

gcc -IE:\ENV\Python25\include -LE:\ENV\Python25\libs farpython.c -lpython25 -shared

Now everything seems fine, but instead of far.pyd or farpython.pyd we've got a.exe Default output filename is easily corrected with yet another option -o

gcc -IE:\ENV\Python25\include -LE:\ENV\Python25\libs farpython.c -lpython25 -shared -o far.pyd

Test.

E:\>python
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import far
>>> far.example("echo")
ECHO is on.
0

Thursday, December 20, 2007

Entrypoint instructions to using C code from Python

Official Python documentation contains everything an experienced C developer needs to build an extension like a module. That means it doesn't cover some basics like compiling code that are essential for startup for beginner.

This tutorial will try to teach and explain steps necessary to make a module in C for Python to call C code from Python program so that later it could be complemented with another tutorial to illustrate steps to call Python from C program. While the order of lessons could be reversed it is really better to start from writing a module (extending Python) to gain general understanding of how Python and C work together.

Let's start with example from http://docs.python.org/ext/simpleExample.html to build a module named "far". We'll define a function "example" that should be accessible from Python interpreter.

// Step 1: A simple example

#include <Python.h>

static PyObject *
far_example(PyObject *self, PyObject *args) {
const char* command;
int sts;

if (!PyArg_ParseTuple(args, "s", &command)) {
return NULL;
}
sts = system(command);
return Py_BuildValue("i", sts);
}

Save example to farpython.c Now we need to compile it somehow. I use cl.exe - Microsoft Visual C++ compiler. It is possible to use other compilers (like GCC) too even though there are warnings http://www.python.org/doc/ext/win-cookbook.html that Python module should be compiled with the same version of compiler that was used to build Python itself. I am not sure if the official distribution of Python 2.5.1 was compiled with my version of VC++ but I gave it a try and it worked. Another day I tried to compile the same code with GCC and it worked too.

To compile we usually do:

cl.exe farpython.c

But in most cases this won't work,

farpython.c(4) : fatal error C1083: Cannot open include file: 'Python.h': No such file or directory

we need to specify where to find Python.h

cl.exe /IE:\ENV\Python25\include farpython.c

This won't produce anything usable either,

LINK : fatal error LNK1104: cannot open file "python25.lib"

because we also need to specify where to find accompanying library with binary code to link with. The required option below is used by the linker. cl.exe treats all options as "for the linker" if they come after /link parameter, which in turn comes after our .c filename.

cl.exe /IE:\ENV\Python25\include farpython.c /link /libpath:E:\ENV\Python25\libs

This won't work too. Nice, eh?

/out:farpython.exe
/libpath:E:\ENV\Python25\libs
farpython.obj
LINK : fatal error LNK1561: entry point must be defined

This means that another key should be passed to the linker. The one that'll tell it that we are creating module or dll and not executable program, so there is no entrypoint to look for.

cl.exe /IE:\ENV\Python25\include farpython.c /link /dll /libpath:E:\ENV\Python25\libs

No errors. Great!

/out:farpython.exe
/dll
/libpath:E:\ENV\Python25\libs
farpython.obj

well, almost. Resulting farpython.exe "can not be executed", because it is actually a dll. Python interpreter wouldn't be able to do anything with it even if it was named farpython.dll To be recognized as Python module the file should have .pyd extension. Let's check this by launching Python from the same directory.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import farpython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named farpython
>>> from shutil import copy
>>> copy("farpython.dll", "farpython.pyd")
>>> import farpython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initfarpython)

While it is possible to rename the file manually, we will add another option for the linker to do the job automatically. The option is /out:farpython.pyd

cl.exe /IE:\ENV\Python25\include farpython.c /link /dll /libpath:E:\ENV\Python25\libs

Although we haven't managed to execute our C function from Python, at least we've convinced Python to recognize our output file as module (even though it was identified as being dead). It's about time to concentrate on our C code, which appears to be incomplete even claimed to be "simple example".

Quite obvious that we need some init function to be present in our C file together with our "example". I'll just make a stub to see what happens. Python looks for something that is called "initfarpython". Ok.

void
initfarpython(void) {

}

Recompile. Launch Python. Import module.

ImportError: dynamic module does not define init function (initfarpython)

Damn. On the second thought everything works as expected. We defined init function in our code, but didn't mention it should be accessible by other programs (i.e. by Python). This is usually done by telling compiler to "export" function. In MS VC++ case with __declspec(dllexport) construction.

__declspec(dllexport) void
initfarpython(void) {

}

Now there is something new from compiler

/out:farpython.exe
/dll
/libpath:E:\ENV\Python25\libs
/out:farpython.pyd
farpython.obj
Creating library farpython.lib and object farpython.exp

It says that our library has something useful for other programs and produces files to allow other programs link to it. But Python doesn't need these files to use the module. Moreover, it doesn't even require that other functions should be explicitly "exported". Quite the opposite - everything except init function should be "declared static", i.e. visible only in module source file.

Before we test and continue we add some options to compiler to make it less verbose. /nologo - removes copyright and compiler version info, /Fefarpython.pyd allows to specify output filename via compiler options rather than through linker.

cl.exe /nologo /IE:\ENV\Python25\include /Fefarpython.pyd farpython.c /link /dll /libpath:E:\ENV\Python25\libs

Starting Python. Importing.

>>> import farpython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: dynamic module not initialized properly

That's logical. What for is initialization function that does nothing? There should be the correct version in official manual. An example of it is in the middle of http://docs.python.org/ext/methodTable.html Adopting it for our case.

PyMODINIT_FUNC
initfarpython(void)
{
(void) Py_InitModule("spam", NULL);
}

There is also a good explanation of the role of init function, so I'll leave it where it belongs. It is also said that PyMODINIT_FUNC is compiler-independent way to define exported init function, a macros that evaluates to "__declspec(dllexport) void" in case of MS VC++.

Using the method above we can safely import the module. Great! Here is the whole listing that compiles and can be imported.

// Step 1: A simple example

#include <python.h>


static PyObject *
far_example(PyObject *self, PyObject *args) {
const char* command;
int sts;

if (!PyArg_ParseTuple(args, "s", &amp;command)) {
return NULL;
}
sts = system(command);
return Py_BuildValue("i", sts);
}


PyMODINIT_FUNC
initfarpython(void) {

(void) Py_InitModule("farpython", NULL);
}

But it's not finished, not yet. The goal is to call "example" function. If you are not already reading manual on http://docs.python.org/ext/methodTable.html then try it. It contains everything that this tutorial is assumed to avoid. This means that the tutorial is almost over.

The last step would be to tell Python what functions are available in module by filling and giving to snake a special structure called "method table". This is done in init function through a parameter that currently reads as NULL. As described on the aforementioned page it looks like:

static PyMethodDef FarMethods[] = {
{"example", far_example, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};

This structure is well described in the manual. The piece of code above should be included after all methods, but before init function - names in C should be defined before they are used in source text. Sentinel here is not just a stub to avoid coding error and missing some params - it really means end of list - without it your module will crash on import.

Final source.



// Step 1: A simple example

#include <python.h>


static PyObject *
far_example(PyObject *self, PyObject *args) {
const char* command;
int sts;

if (!PyArg_ParseTuple(args, "s", &amp;command)) {
return NULL;
}
sts = system(command);
return Py_BuildValue("i", sts);
}



static PyMethodDef FarMethods[] = {
{"example", far_example, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};



PyMODINIT_FUNC
initfarpython(void) {

(void) Py_InitModule("farpython", FarMethods);
}


Test it.

>>> import farpython
>>> dir(farpython)
['__doc__', '__file__', '__name__', 'example']
>>> farpython.example
<built-in function="" example="">
>>> farpython.example()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 1 argument (0 given)
>>> farpython.example("echo")
ECHO is on.
0
>>> ^Z


That's all. The only minor P.S. in the end - the goal was to create "far" module, not "farpython". While I could rename everything from "farpython" to just "far", I need leave the name of the module source file to be "farpython.c" to clearly indicate its purpose inside a heap of other far related sources. But now you should know how to make "far" module out of "farpython.c" with two little fixes.

Sunday, October 28, 2007

Far Manager goes open source

Far Manager of File and Archive Manager - is text mode file manager for windows originally developed by Eugene Roshal.

The news are that from version 1.8 Far Manager goes open source and Unicode! While the project is still in development on SVN it is possible to try this new alpha from http://farmanager.com/farbugs/Far180.b300.x86.rar

Sunday, October 21, 2007

Wanted: Language Transition Function Matrix

The scary name doesn't follow any complicated topic from linear algebra. It merely outlines an idea of a tool for PHP to Java to Python person who wants to get a familiar API on whatever platform the work needs to be done at the moment.

Organized as a snippets repository in matrix form (ok, let's put 'table' for 'matrix') it could conveniently display snippets in a target language that serve as an analogue of functions of a source language. For example, PHP function string file_get_contents($filename) is presented in Python as a :

def file_get_contents(filename):
f = open(filename)
try:
r = f.read( )
finally:
f.close( )
return r

Hovering the PHP API function name could popup a small DHTLM window with function description and a link to official documentation. Main link outside the popup area leads to user content. The resource is a collaborative area that reflects the state of language mappings between different language APIs, allows users to submit their own versions, vote, comment, refactor comments and narrow the scope of original API. It could also allow to work out and point best practices of using languages in specific areas.

I do not know of any resource like this one yet.

Thursday, September 20, 2007

Offline J2ME Google Reader / Gears

Since I do not have much time to implement all crazy ideas by myself, at least I can dedicate some time to describe them for future elaboration in case somebody decides to do something similar and stumble upon a search engine to find out what is already done.

This time it is an idea about bringing Google Reader to J2ME mobile platform, so that feeds can be read and marked offline mode (marked as read or for check in online mode later), preferably downloaded through data cable to keep synchronized with Gears read/marked feeds on PC.

Why mobile and offline? Most of the time we spend time plugged in the Internet, but things are different when you on the move. Theoretically you may use mobile phone to access the Net, but practically it is not always true.

First of all, mobile Internet is quite expensive in many countries. I can say that in my country (located in Europe) 100Mb of mobile traffic may cost from 5% (with monthly fee on dedicated plan) to 105% (use on demand) of average salary for the same operator. 5% is too expensive for just 100Mb.

Second reason is that there are hours underground and airborne where mobile phones are either do not have internet connection or switched to offline plane mode. There are also cases when you run out of money and have nothing to do until nearest ATM. Time spend by mobile in offline is much greater than of working station. If there is a Google Gears for PC then there should be a Gears for mobile, at least a part of mobile Gears.

Well, "maybe" not a "should", but "would" be nice.
Just to keep track of the issue, here a link for original proposal.
http://groups.google.com/group/google-reader-feedback/browse_thread/thread/d9bf21e1b341d38c

Tuesday, August 21, 2007

Installing Darcs. Rootless.

$ wget http://http.us.debian.org/debian/pool/main/d/darcs/darcs_1.0.9-1_i386.deb
$ ar x darcs_1.0.9-1_i386.deb
$ tar -xzfv data.tar.gz
$ cp ./usr/bin/darcs ~/installed/bin/
$ darcs
darcs: error while loading shared libraries: libkrb5support.so.0: cannot open shared object file: No such file or directory

$ ldd ~/installed/bin/darcs
$ wget http://http.us.debian.org/debian/pool/main/k/krb5/libkrb53_1.6.dfsg.1-6_i386.deb
$ ar x libkrb53_1.6.dfsg.1-6_i386.deb; tar -xzvf data.tar.gz
$ cp ./usr/lib/libkrb5support.so.0 ~/installed/lib/
$ darcs
darcs: error while loading shared libraries: libkrb5support.so.0: cannot open shared object file: No such file or directory

# Bad hack - should be used for Darcs only
$ export LD_LIBRARY_PATH=~/installed/lib/darcs; mkdir ~/installed/lib/darcs
$ darcs
darcs: error while loading shared libraries: libssl.so.0.9.8: cannot open shared object file: No such file or directory
$ mv ~/installed/bin/darcs ~/installed/bin/darcs-1.0.9
$ vim ~/installed/bin/darcs
$ cat ~/installed/bin/darcs
#!/bin/sh
# Hack to give Darcs required libraries from home directory.
export LD_LIBRARY_PATH=~/installed/lib/darcs
darcs-1.0.9 $*
$ chmod +x ~/installed/bin/darcs

$ wget "http://http.us.debian.org/debian/pool/main/o/openssl/libssl0.9.8_0.9.8e-6_i386.deb"
$ ar p libssl0.9.8_0.9.8e-6_i386.deb | tar -xzv data.tar.gz
$ mv usr/lib/libssl.so.0.9.8 $LD_LIBRARY_PATH
$ mv usr/lib/libcrypto.so.0.9.8 $LD_LIBRARY_PATH
$ wget http://http.us.debian.org/debian/pool/main/k/keyutils/libkeyutils1_1.2-3_i386.deb
$ ar p libkeyutils1_1.2-3_i386.deb | tar -xzv data.tar.gz
$ mv ./lib/libkeyutils.so.1 $LD_LIBRARY_PATH; mv ./lib/libkeyutils-1.2.so $LD_LIBRARY_PATH

$ darcs get --partial http://darcs.arstecnica.it/tailor
darcs-1.0.9: /usr/lib/libcurl.so.3: no version information available (required by darcs-1.0.9)
darcs-1.0.9: relocation error: darcs-1.0.9: symbol regexec, version GLIBC_2.3.4 not defined in file libc.so.6 with link time reference
# *

# Grrrr..
$ wget http://www.pps.jussieu.fr/~jch/software/files/darcs-1.0.7-i386-linux.gz
$ gzip -d darcs-1.0.7-i386-linux.gz
$ chmod +x darcs-1.0.7-i386-linux
$ mv darcs-1.0.7-i386-linux ~/installed/bin
$ ./darcs-1.0.7-i386-linux get --partial http://darcs.arstecnica.it/tailor
# Outdated, but at least works
$ vim ~/installed/bin/darcs