Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From Python to Mathematica and back again

Tags:

I wrote a Python script, which produces an output that goes to a file. This is read as an input file by Mathematica, that then uses it to make some operations and finally returns another output file. In turn, this last file should be read by the same initial Python script, to perform some more operations.

My question is: what is the simplest (but efficient) way to do that?

I will write in the following a (very simplified) example of what I am dealing with. I start with my python script python_script.py: this produces an array arr that is saved in the file "arr.txt"

import numpy as np 
arr = np.arange(9).reshape(3,3)
np.savetxt('arr.txt', arr, delimiter=' ')

This file is read by my Mathematica notebook nb_Mathematica.nb. This for example could produce another array, in turn saved in another file, "arr2.txt"

file = Import["arr.txt","Table"]
b = ArrayReshape[file, {3,3}]
c = {{1,1,1},{1,1,1},{1,1,1}}
d = b + c
Export["arr2.txt", d]

And now "arr2.txt" must be read by the original Python script. How is it possible to do that? How in particular can I stop the Python script, start Mathematica and then go back to the Python script?

like image 502
johnhenry Avatar asked May 18 '16 23:05

johnhenry


1 Answers

On way to do this:

  • Put your Mathematica code into a plain text file for example make_arr.m
  • Use command line interface of Mathematica:
    • math -script make_arr.m
  • From python invoke the above with the subprocess module
    • subprocess.call(["math", "-script", "make_arr.m"])

Optionally you can use command line arguments in the Mathematica script:

file_name = $CommandLine[[4]]

Further to read

like image 195
BGabor Avatar answered Oct 13 '22 12:10

BGabor