{"id":11187,"date":"2019-12-06T08:05:18","date_gmt":"2019-12-06T13:05:18","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=11187"},"modified":"2019-12-06T08:05:18","modified_gmt":"2019-12-06T13:05:18","slug":"py_addpath","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2019\/12\/06\/py_addpath\/","title":{"rendered":"Py_Addpath"},"content":{"rendered":"<div xmlns:mwsh=\"http:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\n   <introduction><\/p>\n<p><a href=\"http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495\">Sean<\/a>&#8216;s pick this week is <a href=\"http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/62703\"><tt>py_addpath<\/tt> directory matlab_too<\/a> by <a href=\"http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/7926115\">Eric Fields<\/a>.\n      <\/p>\n<p>   <\/introduction><\/p>\n<h3>Using Python with MATLAB<a name=\"1\"><\/a><\/h3>\n<p>Do you have some Python code from a colleague or a snippet from GitHub that you&#8217;d like to use in MATLAB and not have to rewrite it?  You can do that through the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/call-python-libraries.html\">Python Interface<\/a> for MATLAB.\n   <\/p>\n<p>A simple &#8220;hello world&#8221; example is as follows:<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">s = py.str(<span style=\"color: #A020F0\">\"hello world\"<\/span>) <span style=\"color: #228B22\">% Convert MATLAB string to py.str<\/span>\r\nwhos <span style=\"color: #A020F0\">s<\/span>\r\nsc = string(capitalize(s)) <span style=\"color: #228B22\">% Convert capitalized str back to MATLAB string<\/span><\/pre>\n<pre style=\"font-style:oblique\">s = \r\n  Python str with no properties.\r\n\r\n    hello world\r\n  Name      Size            Bytes  Class     Attributes\r\n\r\n  s         1x11                8  py.str              \r\n\r\nsc = \r\n    \"Hello world\"\r\n<\/pre>\n<p>Now what if you want to call your custom Python code?  Well the Python interpreter current working directory is the current MATLAB directory:\n   <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">cwd = py.os.getcwd<\/pre>\n<pre style=\"font-style:oblique\">cwd = \r\n  Python str with no properties.\r\n\r\n    C:\\Documents\\MATLAB\\potw\\PyAddPath\r\n<\/pre>\n<p>So if your code lives here, you&#8217;re all set.  However, you may (probably!) have your Python code somewhere else.  So this is where this week&#8217;s submission comes in.  You can use <tt>py_addpath<\/tt> to add another directory to the Python interpreter&#8217;s path.  Optionally, it can also add the directory to the MATLAB path.\n   <\/p>\n<p>Personally, I&#8217;m no longer modifying the MATLAB path myself and using (and recommending!) <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/projects.html\">Projects<\/a> for anything where path or other setup needs to be configured. Because Projects afford us a &#8220;Run at Startup&#8221; option, I can have it run MATLAB code that takes care of the Python path as well using Eric&#8217;s <tt>py_addpath<\/tt>.\n   <\/p>\n<p>Let&#8217;s take a look at an example. <b>NOTE:<\/b> Everything we&#8217;re doing with Python here could also be done with MATLAB&#8217;s <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/ref\/webread.html\"><tt>webread<\/tt><\/a> but we&#8217;ll pretend we&#8217;re obligated to use this Python function.\n   <\/p>\n<p>Here&#8217;s the Python function:<\/p>\n<pre>\r\n\"\"\"\r\ndataLib.py imports 1-minute bars from GDAX \r\nbuilt with Python 3.5 on 4\/3\/2018\r\n\r\nExample: getPriceData('ETH', '2018-03-16T17:41:26Z', '2018-03-16T18:14:46Z')\r\n\r\nTo call from Python:\r\n&gt;&gt;import dataLib\r\n&gt;&gt;dataLib.getPriceData('ETH', '2018-03-16T17:41:26Z', '2018-03-16T18:14:46Z')\r\n\r\n\"\"\"\r\n\r\ndef getPriceData(product, start, stop):\r\n\timport urllib.request\r\n\timport json\r\n\r\n\t# all cryptocurrency products returned in USD\r\n\tproduct = product + '-USD'\r\n\t\r\n\t# granularity is in seconds, so we are getting 1-minute bars\r\n\tgranularity = '60'\r\n\r\n\t# returns back: [time, low, high, open, close, volume]\r\n\turl = 'https:\/\/api.pro.coinbase.com\/products\/' + product + '\/candles?start=' + start + '&amp;end=' + stop + '&amp;granularity=' + granularity\r\n\r\n\t# execute call to the website\r\n\turlRequest = urllib.request.Request(url, data=None, headers={'User-Agent': 'Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/35.0.1916.47 Safari\/537.36'})\r\n\tresponse = urllib.request.urlopen(urlRequest)\r\n\thtml = response.read()\r\n\r\n\t# python 3.x requires decoding from bytes to string \r\n\tjsonData = json.loads(html.decode())\r\n\treturn jsonData\r\n\r\n###########################################################################################\t\r\n\t\r\ndef parseJson(json_data):\r\n\tfrom array import array\r\n\r\n\t# return back time and close data\r\n\tdates = [row[0] for row in json_data]\r\n\tdata = [row[4] for row in json_data]\r\n\r\n\t# convert to 1D array \r\n\tdateArray = array('d')\r\n\tdataArray = array('d')\r\n\tdateArray.fromlist(dates)\r\n\tdataArray.fromlist(data)\r\n\t\r\n\t# wrap both time series in a dictionary\r\n\tcloseTimeSeries = {'Date': dateArray, 'Close': dataArray}\r\n\treturn closeTimeSeries\r\n<\/pre>\n<p>And here&#8217;s the function I would add to the project startup to add the Python folder at project startup.<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">\r\n<span style=\"color: #0000FF\">function<\/span> addPythonDataLib()\r\nprj = currentProject;\r\npy_addpath(fullfile(prj.RootFolder, <span style=\"color: #A020F0\">'Python'<\/span>));\r\n<span style=\"color: #0000FF\">end<\/span>\r\n\r\n<\/pre>\n<p>Now after opening the project, we can use the <tt>dataLib.py<\/tt> functionality.\n   <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #228B22\">% Query for Ethereum prices<\/span>\r\nstartDate = <span style=\"color: #A020F0\">'2018-03-16T12:00:00Z'<\/span>;\r\nstopDate = <span style=\"color: #A020F0\">'2018-03-16T17:00:00Z'<\/span>;\r\njsonData = py.dataLib.getPriceData(<span style=\"color: #A020F0\">'ETH'<\/span>, startDate, stopDate);\r\ndata = py.dataLib.parseJson(jsonData);\r\n\r\n<span style=\"color: #228B22\">% Convert to MATLAB Data Types<\/span>\r\ndata = struct(data);\r\ndata.Date = double(data.Date)';\r\ndata.Date = datetime(data.Date, <span style=\"color: #A020F0\">'ConvertFrom'<\/span>, <span style=\"color: #A020F0\">'posixtime'<\/span>, <span style=\"color: #A020F0\">'TimeZone'<\/span>, <span style=\"color: #A020F0\">'America\/New_York'<\/span>);\r\ndata.Close = double(data.Close)';\r\ndata = table2timetable(struct2table(data));\r\ndisp(head(data))\r\nstackedplot(data);<\/pre>\n<pre style=\"font-style:oblique\">            Date            Close \r\n    ____________________    ______\r\n    16-Mar-2018 13:00:00     621.1\r\n    16-Mar-2018 12:59:00     621.1\r\n    16-Mar-2018 12:58:00     621.1\r\n    16-Mar-2018 12:57:00    621.09\r\n    16-Mar-2018 12:56:00    621.09\r\n    16-Mar-2018 12:55:00    621.09\r\n    16-Mar-2018 12:54:00    621.06\r\n    16-Mar-2018 12:53:00    621.87\r\n<\/pre>\n<p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/mainPyAddPath_01.png\"> <\/p>\n<p>One suggestion for Eric, is that the function could use <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/ref\/convertstringstochars.html\"><tt>convertStringsToChars<\/tt><\/a> to allow for MATLAB string inputs to be passed in as well without needing to change any algorithmic parts.  I.e.\n   <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">directory = convertStringsToChars(directory);<\/pre>\n<h3>Comments<a name=\"5\"><\/a><\/h3>\n<p>Give it a try and let us know what you think <a href=\"http:\/\/blogs.mathworks.com\/pick\/?p=11187#respond\">here<\/a> or leave a <a href=\"http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/62703#comments\">comment<\/a> for Eric.\n   <\/p>\n<p><script language=\"JavaScript\">\n<!--\n\n    function grabCode_326424e2dc56426b8534874893634af3() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='326424e2dc56426b8534874893634af3 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 326424e2dc56426b8534874893634af3';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = 'Sean de Wolski';\n        copyright = 'Copyright 2019 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\n\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }   \n      \n-->\n<\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><a href=\"javascript:grabCode_326424e2dc56426b8534874893634af3()\"><span style=\"font-size: x-small;        font-style: italic;\">Get<br \/>\n            the MATLAB code<br \/>\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>      Published with MATLAB&reg; R2019b<\/p>\n<\/div>\n<p><!--\n326424e2dc56426b8534874893634af3 ##### SOURCE BEGIN #####\n%% Py_AddPath\n%\n% <http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495 Sean>'s pick this week is\n% <http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/62703 |py_addpath| directory matlab_too> by\n% <http:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/7926115 Eric Fields>.\n% \n\n%% Using Python with MATLAB\n% Do you have some Python code from a colleague or a snippet from GitHub\n% that you'd like to use in MATLAB and not have to rewrite it?  You can do\n% that through the\n% <https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/call-python-libraries.html\n% Python Interface> for MATLAB.\n%\n% A simple \"hello world\" example is as follows:\n\ns = py.str(\"hello world\") % Convert MATLAB string to py.str\nwhos s\nsc = string(capitalize(s)) % Convert capitalized str back to MATLAB string\n\n%%\n% Now what if you want to call your custom Python code?  Well the Python\n% interpreter current working directory is the current MATLAB directory:\n\ncwd = py.os.getcwd\n\n%%\n% So if your code lives here, you're all set.  However, you may (probably!)\n% have your Python code somewhere else.  So this is where this week's\n% submission comes in.  You can use |py_addpath| to add another directory\n% to the Python interpreter's path.  Optionally, it can also add the\n% directory to the MATLAB path.  \n%\n% Personally, I'm no longer modifying the MATLAB path myself and using (and\n% recommending!)\n% <https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/projects.html\n% Projects> for anything where path or other setup needs to be configured.\n% Because Projects afford us a \"Run at Startup\" option, I can have it run\n% MATLAB code that takes care of the Python path as well using Eric's\n% |py_addpath|.\n% \n% Let's take a look at an example. *NOTE:* Everything we're doing with\n% Python here could also be done with MATLAB's\n% <https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/ref\/webread.html\n% |webread|> but we'll pretend we're obligated to use this Python function.\n%\n% Here's the Python function:\n% \n% <include>Python\/dataLib.py<\/include>\n%\n% And here's the function I would add to the project startup to add the\n% Python folder at project startup.\n%\n% <include>addPythonDataLib<\/include>\n%\n% Now after opening the project, we can use the |dataLib.py| functionality.\n\n% Query for Ethereum prices\nstartDate = '2018-03-16T12:00:00Z';\nstopDate = '2018-03-16T17:00:00Z';\njsonData = py.dataLib.getPriceData('ETH', startDate, stopDate);\ndata = py.dataLib.parseJson(jsonData);\n\n% Convert to MATLAB Data Types\ndata = struct(data); \ndata.Date = double(data.Date)';\ndata.Date = datetime(data.Date, 'ConvertFrom', 'posixtime', 'TimeZone', 'America\/New_York');\ndata.Close = double(data.Close)';\ndata = table2timetable(struct2table(data));\ndisp(head(data))\nstackedplot(data);\n\n%%\n% One suggestion for Eric, is that the function could use\n% <https:\/\/www.mathworks.com\/help\/releases\/R2019b\/matlab\/ref\/convertstringstochars.html\n% |convertStringsToChars|> to allow for MATLAB string inputs to be passed\n% in as well without needing to change any algorithmic parts.  I.e.\n%\n%   directory = convertStringsToChars(directory);\n\n%% Comments\n% \n% Give it a try and let us know what you think\n% <http:\/\/blogs.mathworks.com\/pick\/?p=11187#respond here> or leave a\n% <http:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/62703#comments\n% comment> for Eric.\n%\n \n\n##### SOURCE END ##### 326424e2dc56426b8534874893634af3\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/mainPyAddPath_01.png\" onError=\"this.style.display ='none';\" \/><\/div>\n<p>Sean&#8216;s pick this week is py_addpath directory matlab_too by Eric Fields.<\/p>\n<p>Using Python with MATLAB<br \/>\nDo you have some Python code from a colleague or a snippet from GitHub that&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2019\/12\/06\/py_addpath\/\">read more >><\/a><\/p>\n","protected":false},"author":87,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/11187"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=11187"}],"version-history":[{"count":3,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/11187\/revisions"}],"predecessor-version":[{"id":11195,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/11187\/revisions\/11195"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=11187"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=11187"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=11187"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}