Clear Filters
Clear Filters

Keep executing matlab code while python file is running

5 views (last 30 days)
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

Answers (1)

Vatsal on 29 Sep 2023
Edited: Vatsal on 29 Sep 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 = '';
% Create a flag file to indicate the Python script is running
flagFile = 'python_script_running.flag';
fid = fopen(flagFile, 'w');
% Execute Python file as a separate process
system(['python ', pythonfile, ' &']);
while true
if ~isfile(flagFile)
disp('Executing MATLAB commands while Python script is running...');
% Your MATLAB commands here
disp('Python script has finished. Continuing with MATLAB commands...');
% Your MATLAB commands here.
“": -
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):
I hope this helps!




Community Treasure Hunt

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

Start Hunting!