简体   繁体   English

从Python到Mathematica再回来

[英]From Python to Mathematica and back again

I wrote a Python script, which produces an output that goes to a file. 我写了一个Python脚本,它产生一个输出到文件的输出。 This is read as an input file by Mathematica, that then uses it to make some operations and finally returns another output file. 这被Mathematica读取为输入文件,然后使用它来进行一些操作,最后返回另一个输出文件。 In turn, this last file should be read by the same initial Python script, to perform some more operations. 反过来,最后一个文件应该由相同的初始Python脚本读取,以执行更多操作。

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" 我从我的python脚本python_script.py :这会生成一个保存在文件"arr.txt"的数组arr

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 . 该文件由我的Mathematica笔记本nb_Mathematica.nb This for example could produce another array, in turn saved in another file, "arr2.txt" 例如,这可以生成另一个数组,然后保存在另一个文件"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. 现在, "arr2.txt"必须由原始Python脚本读取。 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? 具体如何我可以停止Python脚本,启动Mathematica然后再回到Python脚本?

On way to do this: 在这样做的方式:

  • Put your Mathematica code into a plain text file for example make_arr.m 将Mathematica代码放入纯文本文件中,例如make_arr.m
  • Use command line interface of Mathematica: 使用Mathematica的命令行界面:
    • math -script make_arr.m
  • From python invoke the above with the subprocess module 从python中调用上面的subprocess模块
    • subprocess.call(["math", "-script", "make_arr.m"])

Optionally you can use command line arguments in the Mathematica script: (可选)您可以在Mathematica脚本中使用命令行参数:

file_name = $CommandLine[[4]]

Further to read 进一步阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM