Skip to content

Instantly share code, notes, and snippets.

@lebarsfa
Forked from jaeandersson/import.m
Last active March 6, 2024 22:14
Show Gist options
  • Save lebarsfa/ebc19b143df77753842f920b4b680b84 to your computer and use it in GitHub Desktop.
Save lebarsfa/ebc19b143df77753842f920b4b680b84 to your computer and use it in GitHub Desktop.
Import a package into Octave using the syntax "import packagename.*" or "import py.packagename.*" if using Pythonic
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