LoginSignup
6
5

More than 5 years have passed since last update.

Common LispからPythonを呼び出す備忘録

Last updated at Posted at 2017-06-14

burgled-batteriesなるCommon LispにPythonを埋め込むことのできるライブラリを見つけたので試してみました.その備忘録です.

環境

$ ros --version
roswell 17.5.8.78
$ ros run -- --version
SBCL 1.3.18
$ python --version
Python 2.7.13

burgled-batteriesのインストールはroswellから簡単にできます.

$ ros install burgled-batteries

Common LispからPythonの呼び出し

以下のモジュールから関数を呼び出してみます.

hello.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def hello(name):
    print "Hi, {}! This is Python.".format(name)

以下,SBCLのREPLです.

CLからPythonの関数を実行
* (ql:quickload :burgled-batteries)
To load "burgled-batteries":
  Load 1 ASDF system:
    burgled-batteries
; Loading "burgled-batteries"
...
(:BURGLED-BATTERIES)
* (in-package :burgled-batteries)

* (startup-python) ;; Pythonインタプリタを起動
* (import "sys") ;; sysモジュールをインポート

0
* (run "sys.path.append('./')") ;; インポート時になぜかカレントディレクトリを検索しないので追加
                                ;; runは埋め込み文字列を現在のインタプリタで実行する

* (import "hello") ;; helloモジュールをインポート

* (run "hello.hello('Kojiro')") ;; hello.helloを呼び出し
Hi, Kojiro! This is Python.

埋め込むだけでなく関数として定義して呼び出すこともできます.

CLでPythonの関数を定義して呼び出し
* (defpyfun "hello.hello" (name)) ;; hello.pyのhelloをhello.helloとして定義

HELLO.HELLO
* (hello.hello "Kojiro") ;; 普通に呼び出せる
Hi, Kojiro! This is Python.
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5