Porably importing modules
Ignacio Vazquez-Abrams
ignacio at openservices.net
Thu Aug 23 13:00:32 EDT 2001
On Thu, 23 Aug 2001, Graham Ashton wrote:
> I'm sure there's a more idiomatic way to trap the failure to import a
> module than my attempt. Whilst making sure one of my apps runs on Windows
> as well as Unix I came up with the following code (re-typed and untested):
>
> # catch failure to import and let it pass
> try:
> import syslog
> except ImportError, e:
> print "can't import syslog: %s" % e
>
> # [ snip loads of stuff ]
>
> # make sure syslog is imported before trying to use it
> if "syslog" in dir():
> syslog.openlog(...)
> else:
> print "sorry, no syslog support"
>
> Am I re-inventing a perfectly round wheel? Is there a cleaner way?
>
> Thanks.
>
> --
> Graham
Try this:
def dummyzero():
pass
def dummyone(x):
pass
log=None
closelog=None
...
try:
import syslog
log=syslog.syslog
closelog=syslog.close
syslog.open(...)
except ImportError, e:
print "can't import syslog: %s" % e
log=dummyone
closelog=dummyzero
...
log("Whoops! THAT wasn't supposed to happen...")
...
closelog()
--
Ignacio Vazquez-Abrams <ignacio at openservices.net>
More information about the Python-list
mailing list