0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WolframScriptの関数をPythonコードから呼ぶ

Last updated at Posted at 2025-07-28
  1. 解説記事
    1. https://www.wolfram.com/engine/faq/index.php.ja
    2. https://reference.wolfram.com/language/WolframClientForPython/
  2. 準備
    1. Wolfram ID(無料)を取得する
    2. Wolfram Engineをダウンロードし、WolframScriptとともにインストールする
    3. Wolfram Engineを立ち上げる(取得したIDでログインする)
      https://support.wolfram.com/ja/46070
    4. pythonのパッケージwolframclientをインストールする
      pip3 install wolframclient
      
  3. wolframscriptコード
    minimal_calculation.wls
     (* minimal_calculation.wls - ミニマルな関数定義ファイル *)
    
     (* 簡単な数値計算を行う関数 *)
     simpleCalculation[x_] := 
         Module[{result},
             (* 簡単な計算例: x^2 + 2*x + 1 を計算 *)
             result = x^2 + 2*x + 1;
     
             (* 数値として返す *)
             N[result]
       ];
    
     Print["Simple calculation function loaded successfully."];
    
  4. pythonコード
    minimal_test.py
    #!/usr/bin/env python3
    # minimal_test.py
    
    from wolframclient.evaluation import WolframLanguageSession
    from wolframclient.language import wlexpr
    
    def main():
        # Mathematica セッション開始
        session = WolframLanguageSession()
        
        # 関数読み込み
        session.evaluate(wlexpr('<< "minimal_calculation.wls";'))
        
        # 引数を指定して関数を1回だけ呼び出し
        x_value = 5.0
        expr = f'simpleCalculation[{x_value}]'
        result = session.evaluate(wlexpr(expr))
        
        # 結果を表示
        print(f"Input: x = {x_value}")
        print(f"Result: {result}")
        
        # セッション終了
        session.terminate()
    
    if __name__ == '__main__':
        main()
    
  5. wolframscriptとpythonコードは同じディレクトリ置く
  6. pythonコードの実行
    python3 minimal_test.py
    
    (結果)
    Input: x = 5.0
    Result: 36.0
    
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?