MATLAB Answers

why does my python import fail when deployed?

2 views (last 30 days)
John Anderson
John Anderson on 24 Jun 2019
Commented: John Anderson on 24 Jun 2019
I am making use of some python code for recovering data from a BME280 sensor. The matlab code below code executes without any problem from my copy of Matlab running on a PC.
function blinkLED1() %#codegen
% create log file
if coder.target( 'MATLAB' )
fidLog = fopen( 'blinkLED_pc.log', 'w' );
fprintf( fidLog, '%s \n', 'running on pc' );
else
fidLog = fopen( 'blinkLED_pi.log', 'w' );
fprintf( fidLog, '%s \n', 'running on pi' );
end
% Create a Raspberry Pi object
r= raspi();
% Turn on the LED
fprintf( fidLog, '%s \n', 'turning on LED' );
writeLED(r,"LED0", 1);
% sleep of 0.5 seconds
fprintf( fidLog, '%s \n', 'sleeping for 0.5 seconds' );
system(r, 'sleep 0.5' );
% Turn off the LED
fprintf( fidLog, '%s \n', 'turning off LED' );
writeLED(r,"LED0", 0);
result = system( r, 'pwd' );
fprintf( fidLog, '%s \n', result );
% get some temperature, pressure and humidity data from bme280
result = system( r, 'python bme280.py' );
fprintf( fidLog, '%s \n', result );
fclose( fidLog );
log file
------------
running on pc
turning on LED
sleeping for 0.5 seconds
turning off LED
/home/pi
Chip ID : 96
Version : 0
Temperature : 23.33 C
Pressure : 1009.74914285 hPa
Humidity : 61.858241144 %
-------------------
I have no problem deploying this code via the usual route (board = targetHardware('Raspberry Pi' ), deploy(board,'blinkLED1' )). However, on execution on the pi the python call fails due to an import error.
log file
-------------
running on pi
turning on LED
sleeping for 0.5 seconds
turning off LED
/home/pi
Traceback (most recent call last):
File "/home/pi/bme280.py", line 21, in <module>
import smbus
ImportError: No module named smbus
---------------------
I have checked that the module smbus is on the sys.path (under /home/pi/.local/lib/python2.7/site-packages) and it is obviously visible when I attempt execution from the PC. It is not obvious to me why this should fail when deployed.

  1 Comment

John Anderson
John Anderson on 24 Jun 2019
This seems rather strange but when executing the python code from deployed matlab code the python path defined under sys.path is modified so that some of the paths to certain libraries are lost.
Adding a call to append an appropraite library location to the python code seems to fix the problem. Any views on why this path information is lost when would be welcome.
import sys
# append path to enable impot of smbus
sys.path.append('/home/pi/.local/lib/python2.7/site-packages')
import smbus

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!