From Python to Mathematica and vice versa

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

My question is: what is the easiest (but effective) way to do this?

I will write in the following (very simplified) example of what I mean. I start with my python script python_script.py: it creates an array arrthat is saved in a 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 laptop nb_Mathematica.nb. For example, this can lead to the creation of another array, which in turn is stored 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"should be read by the original Python script. How can I do that? How, in particular, can I stop the Python script, run Mathematica, and then return to the Python script?

+4
source share
1 answer

To do this:

  • Put the Mathematica code in a text file like make_arr.m
  • Use the Mathematica command line interface:
    • math -script make_arr.m
  • From python is called above with subprocess
    • subprocess.call(["math", "-script", "make_arr.m"])

Optionally, you can use command line arguments in a Mathematica script:

file_name = $CommandLine[[4]]

Read further

+3

All Articles