du1913 2016-04-09 20:54
浏览 71

无法在脚本中导入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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料