python-tldp/tldp/utils.py

52 lines
1.2 KiB
Python
Raw Normal View History

2016-02-11 03:22:23 +00:00
#! /usr/bin/python
from __future__ import absolute_import, division, print_function
2016-02-12 18:31:50 +00:00
import os
2016-02-12 21:24:09 +00:00
import io
2016-02-11 03:22:23 +00:00
import sys
import logging
def getLogger(**opts):
level = opts.get('level', logging.INFO)
logging.basicConfig(stream=sys.stderr, level=level)
logger = logging.getLogger()
return logger
logger = getLogger()
2016-02-12 18:31:50 +00:00
def is_executable(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
def which(program):
'''return None or the full path to an executable (respecting $PATH)
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028
'''
fpath, fname = os.path.split(program)
if fpath and is_executable(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
sut = os.path.join(path, program)
if is_executable(sut):
return sut
return None
def makefh(thing):
2016-02-12 21:24:09 +00:00
if isinstance(thing, io.IOBase):
2016-02-12 18:31:50 +00:00
f = thing
elif isinstance(thing, str) and os.path.isfile(thing):
f = open(thing)
else:
raise TypeError("Cannot make file from %s of %r" %
2016-02-12 18:31:50 +00:00
(type(thing), thing,))
return f
2016-02-11 03:22:23 +00:00
#
# -- end of file