Import a package into Octave using the syntax "import packagename.*" or "import py.packagename.*" if using Pythonic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function import(varargin) | |
% Import a package. Only entire packages can be imported currently. | |
error(nargchk(1,inf,nargin,'struct')); | |
% Import the packages one-by-one. | |
for i=1:nargin | |
[pkgname,names]=import1(varargin{i}); | |
% Pythonic specific case... | |
for j=1:length(names) | |
assignin('caller',char(names{j}),pyeval({[pkgname '.' char(names{j})]})); | |
end | |
end | |
end | |
function [pkgname,names]=import1(pkgname) | |
names={}; | |
pkgname_parts=strsplit(pkgname,'.'); | |
% Pythonic specific case... | |
if strcmp(pkgname_parts{1},'py') | |
b_pythonic=true; | |
pkg load pythonic; | |
pkgname_parts=pkgname_parts(2:end); | |
else | |
b_pythonic=false; | |
end | |
if length(pkgname_parts)~=2||~strcmp(pkgname_parts{end},'*') | |
error('Only the syntax ''import packagename.*'' or ''import py.packagename.*'' (if using Pythonic) are currently supported'); | |
end | |
pkgname=pkgname_parts{1}; | |
if b_pythonic | |
pyexec(['import ' pkgname]); | |
names=pyeval(['dir(' pkgname ')']); | |
else | |
% Get path for package. | |
pkgpath=locatepkg(pkgname); | |
% Add to path. | |
addpath(pkgpath); | |
end | |
end | |
function pkgpath=locatepkg(pkgname) | |
pathdirs=strsplit(path, pathsep); | |
for iPath=1:length(pathdirs) | |
pkgpath=[pathdirs{iPath} filesep '+' pkgname]; | |
if exist(pkgpath,'dir') | |
return; | |
end | |
end | |
error('Package ''%s'' cannot be located in the path', pkgname); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment