Keep executing matlab code while python file is running

4 visualizzazioni (ultimi 30 giorni)
I want to perform soft-synchronization between MATLAB & Python in the following manner in the .m file. Is there a way to do this?
run certain matlab commands ;
pyrun(pythonfile) % a python program
while pythonfile is running:
execute matlab commands
end

Risposte (1)

Vatsal
Vatsal il 29 Set 2023
Modificato: Vatsal il 29 Set 2023
I understand that you want to run a Python file from the MATLAB script file and while this Python file is running, you want to run some MATLAB commands in parallel. There is no direct way to check whether the Python file is running or not, but you can create a flag file to indicate the status of the Python script. I am attaching the sample code of both the MATLAB file and python file below:
"Example.m": -
disp('Running MATLAB commands...');
% Your MATLAB commands here
disp('Running Python file in parallel...');
pythonfile = 'main.py';
% Create a flag file to indicate the Python script is running
flagFile = 'python_script_running.flag';
fid = fopen(flagFile, 'w');
fclose(fid);
% Execute Python file as a separate process
system(['python ', pythonfile, ' &']);
while true
if ~isfile(flagFile)
disp("done")
break;
end
disp('Executing MATLAB commands while Python script is running...');
% Your MATLAB commands here
end
disp('Python script has finished. Continuing with MATLAB commands...');
% Your MATLAB commands here.
“Main.py": -
import time
import os
# Run for 20 seconds
start_time = time.time()
while time.time() - start_time < 20:
# Check if it's been 5 seconds
if time.time() - start_time >= 5:
print("Reached 5 seconds!")
# Continue with other operations or code her
# Delete the flag file upon completion
flag_file = 'python_script_running.flag'
if os.path.isfile(flag_file):
os.remove(flag_file)
I hope this helps!

Prodotti


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by