无法在脚本中导入matplotlib

I am working on a project that involved generating charts of information automatically, as well as other analytical information. In order to accomplish that, I have a set of scripts called automatically from one main script. One of these, generating all the charts, is named analysis.py, utilizing the matplotlib library. But for some reason, it is not running.

Here is the beginning of the file where I import matplotlib:

#!/usr/bin/python
import csv
from datetime import datetime
import numpy as np
import convert
from itertools import groupby

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

Whenever I run this script manually in the shell, it works just fine:

root@ubuntu:/var/www/Project$ python /var/www/Project/analysis.py
root@ubuntu:/var/www/Project$ 

Also, when I import matplotlib manually it also works fine:

root@ubuntu:/var/www/Project$ python
Python 2.7.3 (default, Jun 22 2015, 19:33:41) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> from matplotlib.backends.backend_pdf import PdfPages
>>>

But whenever analysis.py is called from whatever locations (PHP script, another python script, etc.) it fails at the import statmenet for matplotlib. It doesn't return any error message (or I don't know how to access them), but I have isolated the error occurs at the import statment for matplotlib by trial and error.

So why doesn't matplotlib import in some situations, and how do I work around it?

Update:

I have discovered that calling the script from php and python produces problems for different reasons. From php, I used this script here:

$input = 'python /var/www/Project/analysis.py';
$command = escapeshellcmd($input);
$output = shell_exec($command);
echo '<pre>'.$output.'</pre>';

This is where the script failed to import the library matplotlib in the analysis.py. This is true even when I called analysis.py from a different python script (test.py), which in turn is called in the php.

But when I run test.py directly:

import os
command = "python /var/www/Project/analysis.py"
os.system(command)

This time the matplotlib imports, but a different problem occurs. Whenever I try to read a particular file, it returns an empty string:

with open("/var/www/Project/profile_data.txt") as csvfile:
reader = csv.reader(csvfile)
next(reader)

Because I get this error:

next(reader)
StopIteration

Which means the file is empty, when it clearly isn't.