[英]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: 在这样做的方式:
make_arr.m
make_arr.m
math -script make_arr.m
subprocess
module subprocess
模块
subprocess.call(["math", "-script", "make_arr.m"])
Optionally you can use command line arguments in the Mathematica script: (可选)您可以在Mathematica脚本中使用命令行参数:
file_name = $CommandLine[[4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.