Pyrun - error when running python script

조회 수: 47 (최근 30일)
Marcin Kowalski
Marcin Kowalski 2022년 9월 23일
댓글: Bala Tripura Bodapati 2022년 9월 28일
Hi,
I am trying to run a python script from MATLAB. The script aims to setup a websocket server.
>> pyrun('webs_server.py')
Error using <string>><module> (line 1)
Python Error: NameError: name 'webs_server' is not defined
Python script runs fine when run under Conda.
My pyenv is following:
ans =
PythonEnvironment with properties:
Version: "3.9"
Executable: "C:\Users\kowal\AppData\Local\Programs\Python\Python39\python.EXE"
Library: "C:\Users\kowal\AppData\Local\Programs\Python\Python39\python39.dll"
Home: "C:\Users\kowal\AppData\Local\Programs\Python\Python39"
Status: Loaded
ExecutionMode: InProcess
ProcessID: "15984"
ProcessName: "MATLAB"
The directory with the script is in the path. What could be the possible issue?

채택된 답변

Bala Tripura Bodapati
Bala Tripura Bodapati 2022년 9월 26일
Hi Marcin
It is my understanding that you would like to execute Python script from MATLAB and are encountering an error while using the 'pyrun' function.
The 'pyrun' function is used to execute Python commands from MATLAB. To execute a Python script file, the 'pyrunfile' function is used. The filename of the code snippet should be passed as an argument to the 'pyrunfile' function. The following code illustrates the usage of the 'pyrunfile' function:
>>pyrunfile('webs_server.py')
Please refer the pyrunfile documentation for more information.
  댓글 수: 2
Marcin Kowalski
Marcin Kowalski 2022년 9월 26일
Thank you! I have no idea how I could missed this function.
Anyways, I made a step forward, but found another issue:
Python Error: ModuleNotFoundError: No module named 'websocket_server'
This is quite strange because the module is installed and added to the path. Is there any chance to see which modules/dependencies are visible for MATLAB?
Bala Tripura Bodapati
Bala Tripura Bodapati 2022년 9월 28일
Hi Marcin,
It is my understanding that 'ModuleNotFoundError' error is encountered.In order to verify the libraries that are visible to MATLAB, ensure that the libraries are there in the Python sys.path :
py.sys.path
If not, you can install the libraries in the Python system path.
This issue can also be encounterd if more than 2 versions of Python are installed on your system.The right version can be configured using the following command:
pyenv('Version', 'C:\ProgramData\Anaconda3\python.exe')
Please refer below documentation for more information:

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by