-1

Is it possible to do try exception (or something else) if a module exists or not? I have a code as(all of them are defined, just not included here):

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()

It writes foo.dat and also plots it. What I am trying to achieve is:

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()

Can I do that?

BaRud
  • 3,055
  • 7
  • 41
  • 89
  • 1
    Look here ... http://stackoverflow.com/questions/14050281/how-to-check-if-a-python-module-exists-without-importing-it – LordWilmore Jul 05 '16 at 09:04

1 Answers1

0

Importing a module that does not exist will raise ImportError, which you can catch like any other exception with a try/except block.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895