Skip to content
Snippets Groups Projects
Commit 7100a9de authored by Alexis GAMELIN's avatar Alexis GAMELIN
Browse files

Add function to send commands to matlab from python

parent 49d983cf
Branches
Tags
No related merge requests found
*.pyc
#!/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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment