Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python libraries in Racket

Tags:

python

racket

ffi

Can I use Python code and libraries in Racket? I have installed PyonR (https://github.com/pedropramos/PyonR) in DrRacket so I can choose "#lang python" and run Python code. But how can I combine Racket and Python language codes for my application?

There is also a limited Python to Lisp translator at https://github.com/nurv/pnil . Is there something similar for Racket?


Edit: As advised in comments, I tried following. This python code in file "pysamples.rkt" works well in DrRacket:

#lang python

def greet(name):
    print 'Hello', name

greet('Alfred')

Output:

Hello Alfred

I tried using above definition in Racket code, but it did not work. Following is the Racket code:

#lang racket
; (require python/config) (enable-cpyimport!) ; ran this once; worked.

(#%require "pysamples.rkt")
(greet "Racket_code")

The error is:

greet: unbound identifier in module in: greet
like image 906
rnso Avatar asked Dec 24 '22 02:12

rnso


1 Answers

The PyonR project is the closest ready-to-use way of using Python libraries from Racket that I know of. However note that there is a difference between Python libraries written in Python and Python libraries that are a thin Python layer on top of a C library. As you have experienced the latter type is not working (to my knowledge at least - but Pedro is the one to ask).

If you need to use a library written in language X (for X could be Python) you can always write a "listener" program in language X that waits for messages from a Racket program, and when a message is received, computes an answer and sends it back to the Racket program. How to send and receive messages is up to you, but a simple option is to have two files, one "R-to-X" which Racket writes to and X reads from, and another "X-to-R" where Racket receives the messages.

This approach has some overhead, but if the computation takes longer than sending the message, then it is a viable solution.

like image 129
soegaard Avatar answered Dec 28 '22 06:12

soegaard