Keep executing matlab code while python file is running
조회 수: 4 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
Vatsal
2023년 9월 29일
편집: Vatsal
2023년 9월 29일
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!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!