diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0d20b6487c61e7d1bde93acf4a14b7a89083a16d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.pyc diff --git a/matlab.py b/matlab.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb48aec820d9eca55d93abd885cd75da796e4f6 --- /dev/null +++ b/matlab.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Wed Jun 5 14:06:14 2024 + +@author: gamelina +""" + +import subprocess +import os +from pathlib import Path + +def __write_mat_file(matlab_command): + path = Path(os.getcwd()) / "temp_matlab_file.m" + with open(path, "w") as file: + file.write("cd(getenv('MLROOT'));") + file.write('\n') + file.write("setpathsoleil('StorageRing');") + file.write('\n') + file.writelines(matlab_command) + file.write('\n') + file.write("quit force") + return path + +def to_matlab(matlab_command, remove_temp_file=True, verbiose=False): + """ + Send command to be exectued in matlab from python. + + Parameters + ---------- + matlab_command : str or array-like of str + Matlab commands to be exectued. + If array-like (list, arrays, ...) then each line must be separeted by '\n'. + remove_temp_file : bool, optional + If True, delete matlab temporay file at the end of function. + The default is True. + verbiose : bool, optional + Print out content of matlab file and bash command. + The default is False. + + Returns + ------- + None. + + """ + temp_file = __write_mat_file(matlab_command) + if verbiose: + print("matlab script:") + with open(temp_file, 'r') as file: + print(file.read()) + string = f"'{str(temp_file)}'" + command = f'/home/configuration/bin/matlab2018b -nosplash -r "run({string}); exit;"' + if verbiose: + print("bash command:") + print(command) + subprocess.call(command, shell=True) + # this actually wait for matlab to close + if remove_temp_file: + os.remove(temp_file) \ No newline at end of file