【问题标题】:exception if module does not exist如果模块不存在则异常
【发布时间】:2016-11-07 01:00:25
【问题描述】:

如果模块存在或不存在,是否可以尝试异常(或其他)? 我有一个代码(所有这些都已定义,只是不包括在此处):

import matplotlib.pyplot as plt
import numpy as np

def scf:
    A = np.array(plist, dtype="float")
    np.savetxt("foo.dat", A,
                delimiter=' ', fmt="%1.4e")

    plt.plot(A[:, 0], A[:, 4], label="foo", linewidth="4.")
    plt.show()

它写入foo.dat 并绘制它。我想要实现的是:

def scf:
    A = np.array(plist, dtype="float")
    # if matplotlib does not exists, write to file
    np.savetxt("foo.dat", A,
                delimiter=' ', fmt="%1.4e")
    #else if matplotlib exists, show plot, dont write to file
    plt.plot(A[:, 0], A[:, 4], label="foo", linewidth="4.")
    plt.show()

我可以这样做吗?

【问题讨论】:

标签: python python-module


【解决方案1】:

导入不存在的模块将引发ImportError,您可以像使用 try/except 块一样捕获任何其他异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多