Capdi
Capdi

Reputation: 257

Calling Matlab scripts from Django with Python's Popen class

I'm developing a Django app which runs Matlab scripts with Python's Popen class. The python script that calls Matlab scripts lives in the main folder of my Django app (with views.py). When I call the script from command line, it runs like a charm but when I make a request from the client in order to run the corresponding python script, I receive the following warning:

"< M A T L A B (R) > Copyright 1984-2018 The MathWorks, Inc. R2018a (9.4.0.813654) 64-bit (glnxa64) February 23, 2018 To get started, type one of these: helpwin, helpdesk, or demo. For product information, visit www.mathworks.com. >> [Warning: Unable to create preferences folder in /var/www/.matlab/R2018a. Preferences folder location must be writable. Using a temporary preferences folder for this MATLAB session. See the preferences documentation for more details.] >>

My app uses a Python virtual environment and it is being deployed with Apache web server. Here is my python script that calls Matlab scripts:

import os
import subprocess as sp
import pymat_config

def pymat_run():
    pwd = pymat_config.pwd_config['pwd']

    cmd1 = "-r \"Arg_in = '/path/to/my/main/folder/input.txt'; Arg_out = '/path/to/my/main/folder/file.txt';  matlab_script1\""

    baseCmd1 = ['/usr/local/MATLAB/R2018a/bin/matlab', '-nodesktop', '-nosplash', '-nodisplay', 'nojvm', cmd1]

    os.chdir('/path/to/matlab_script1')

    sudo_cmd = sp.Popen(['echo', pwd], stdout=sp.PIPE)
    exec1 = sp.Popen(['sudo', '-S'] + baseCmd1, stdin=sudo_cmd.stdout, stdout=sp.PIPE, stderr=sp.PIPE)
    out, err = exec1.communicate()

    return out

Any suggestions ?

Upvotes: 2

Views: 671

Answers (1)

Capdi
Capdi

Reputation: 257

Finally I managed to find the solution of that issue by myself. The problem came from the kind of user who called the Matlab's script. When I was running the above script from a Python interpreter or from the shell, it was the user (with the user password) who was running the script while when I was calling the script from the client the user was the web server's user: www-data. So at first to avoid the above warning I gave permissions to www-data user to the /var/www folder with the following command:

sudo chown -R www-data /var/www/

After that, the "Warning" disappeared but the script still didn't run because it was asking for www-data's password internally and taking user's password from pymat_config file. To solve this, I edited /etc/sudoers file in order for www-data to be able to call Matlab scripts without asking password. So I added the following line:

www-data ALL=(ALL) NOPASSWD: /usr/local/MATLAB/R2018a/bin/matlab

and now it runs like a charm !

Upvotes: 2

Related Questions