Skip to content

Commit 39938bf

Browse files
committed
Merge pull request #119 from yarikoptic/_enh/dft_use_logging
dicomfs: control its verbosity from cmdline (silent by default) + use python's logging otherwise it bombards user with lots of information he doesn't need (ideally it also should fall into background unless -f (not yet present) or any -v provided)
2 parents 4561dad + b21d5e7 commit 39938bf

File tree

2 files changed

+75
-48
lines changed

2 files changed

+75
-48
lines changed

bin/dicomfs

Lines changed: 62 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,21 @@ import stat
1515
import errno
1616
import time
1717
import locale
18+
import logging
1819
import fuse
20+
import nibabel as nib
1921
import nibabel.dft as dft
2022

23+
from optparse import OptionParser, Option
24+
2125
uid = os.getuid()
2226
gid = os.getgid()
2327
encoding = locale.getdefaultlocale()[1]
2428

2529
fuse.fuse_python_api = (0, 2)
2630

31+
logger = logging.getLogger('nibabel.dft')
32+
2733
class FileHandle:
2834

2935
def __init__(self, fno):
@@ -78,33 +84,31 @@ class DICOMFS(fuse.Fuse):
7884
def match_path(self, path):
7985
wd = self.get_paths()
8086
if path == '/':
81-
print 'return root'
87+
logger.debug('return root')
8288
return wd
8389
for part in path.lstrip('/').split('/'):
84-
print path, part
90+
logger.debug("path:%s part:%s" % (path, part))
8591
if part not in wd:
8692
return None
8793
wd = wd[part]
88-
print 'return'
94+
logger.debug('return')
8995
return wd
9096

9197
def readdir(self, path, fh):
92-
print 'readdir'
93-
print path
98+
logger.info('readdir %s' % (path,))
9499
matched_path = self.match_path(path)
95100
if matched_path is None:
96101
return -errno.ENOENT
97-
print 'match', matched_path
102+
logger.debug('matched %s' % (matched_path,))
98103
fnames = [ k.encode('ascii', 'replace') for k in matched_path.keys() ]
99104
fnames.append('.')
100105
fnames.append('..')
101106
return [ fuse.Direntry(f) for f in fnames ]
102-
107+
103108
def getattr(self, path):
104-
print 'getattr'
105-
print 'path:', path
109+
logger.debug('getattr %s' % path)
106110
matched_path = self.match_path(path)
107-
print matched_path
111+
logger.debug('matched: %s' % (matched_path,))
108112
now = time.time()
109113
st = fuse.Stat()
110114
if isinstance(matched_path, dict):
@@ -137,10 +141,9 @@ class DICOMFS(fuse.Fuse):
137141
st.st_nlink = 1
138142
return st
139143
return -errno.ENOENT
140-
144+
141145
def open(self, path, flags):
142-
print 'open'
143-
print path
146+
logger.debug('open %s' % (path,))
144147
matched_path = self.match_path(path)
145148
if matched_path is None:
146149
return -errno.ENOENT
@@ -157,34 +160,56 @@ class DICOMFS(fuse.Fuse):
157160

158161
# not done
159162
def read(self, path, size, offset, fh):
160-
print 'read'
161-
print path
162-
print size
163-
print offset
164-
print fh
163+
logger.debug('read')
164+
logger.debug(path)
165+
logger.debug(size)
166+
logger.debug(offset)
167+
logger.debug(fh)
165168
return self.fhs[fh.fno][offset:offset+size]
166169

167170
def release(self, path, flags, fh):
168-
print 'release'
169-
print path
170-
print fh
171+
logger.debug('release')
172+
logger.debug(path)
173+
logger.debug(fh)
171174
del self.fhs[fh.fno]
172175
return
173-
174-
progname = os.path.basename(sys.argv[0])
175-
if len(sys.argv) != 3:
176-
sys.stderr.write('usage: %s <directory containing DICOMs> <mount point>\n' % progname)
177-
sys.exit(1)
178-
179-
fs = DICOMFS(dash_s_do='setsingle')
180-
fs.parse(['-f', '-s', sys.argv[2]])
181-
fs.dicom_path = sys.argv[1].decode(encoding)
182-
try:
183-
fs.main()
184-
except fuse.FuseError:
185-
# fuse prints the error message
186-
sys.exit(1)
187-
188-
sys.exit(0)
176+
177+
def get_opt_parser():
178+
# use module docstring for help output
179+
p = OptionParser(
180+
usage="%s [OPTIONS] <DIRECTORY CONTAINING DICOMSs> <mount point>"
181+
% os.path.basename(sys.argv[0]),
182+
version="%prog " + nib.__version__)
183+
184+
p.add_options([
185+
Option("-v", "--verbose", action="count",
186+
dest="verbose", default=0,
187+
help="make noise. Could be specified multiple times"),
188+
])
189+
190+
return p
191+
192+
if __name__ == '__main__':
193+
parser = get_opt_parser()
194+
(opts, files) = parser.parse_args()
195+
196+
if opts.verbose:
197+
logger.addHandler(logging.StreamHandler(sys.stdout))
198+
logger.setLevel(opts.verbose > 1 and logging.DEBUG or logging.INFO)
199+
200+
if len(files) != 2:
201+
sys.stderr.write("Please provide two arguments:\n%s\n" % parser.usage)
202+
sys.exit(1)
203+
204+
fs = DICOMFS(dash_s_do='setsingle')
205+
fs.parse(['-f', '-s', files[1]])
206+
fs.dicom_path = files[0].decode(encoding)
207+
try:
208+
fs.main()
209+
except fuse.FuseError:
210+
# fuse prints the error message
211+
sys.exit(1)
212+
213+
sys.exit(0)
189214

190215
# eof

nibabel/dft.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from os.path import join as pjoin
1515
import tempfile
1616
import getpass
17+
import logging
1718
import warnings
1819
import sqlite3
1920

@@ -27,6 +28,7 @@
2728
from .optpkg import optional_package
2829
dicom, have_dicom, _ = optional_package('dicom')
2930

31+
logger = logging.getLogger('nibabel.dft')
3032

3133
class DFTError(Exception):
3234
"base class for DFT exceptions"
@@ -153,7 +155,7 @@ def as_nifti(self):
153155
for (i, si) in enumerate(self.storage_instances):
154156
if i + 1 != si.instance_number:
155157
raise InstanceStackError(self, i, si)
156-
print 'reading %d/%d' % (i+1, len(self.storage_instances))
158+
logger.info('reading %d/%d' % (i+1, len(self.storage_instances)))
157159
d = self.storage_instances[i].dicom()
158160
data[i, :, :] = d.pixel_array
159161

@@ -288,7 +290,7 @@ def update_cache(base_dir):
288290
for dir in sorted(mtimes.keys()):
289291
if dir in db_mtimes and mtimes[dir] <= db_mtimes[dir]:
290292
continue
291-
print 'updating %s' % dir
293+
logger.debug('updating %s' % dir)
292294
_update_dir(c, dir, files_by_dir[dir], studies, series, storage_instances)
293295
if dir in db_mtimes:
294296
query = "UPDATE directory SET mtime = ? WHERE path = ?"
@@ -332,20 +334,20 @@ def get_studies(base_dir=None):
332334
return studies
333335

334336
def _update_dir(c, dir, files, studies, series, storage_instances):
335-
print dir
337+
logger.debug('Updating directory %s' % dir)
336338
c.execute("SELECT name, mtime FROM file WHERE directory = ?", (dir, ))
337339
db_mtimes = dict(c)
338340
for fname in db_mtimes:
339341
if fname not in files:
340-
print ' remove %s' % fname
342+
logger.debug(' remove %s' % fname)
341343
c.execute("DELETE FROM file WHERE directory = ? AND name = ?",
342344
(dir, fname))
343345
for fname in files:
344346
mtime = os.lstat('%s/%s' % (dir, fname)).st_mtime
345347
if fname in db_mtimes and mtime <= db_mtimes[fname]:
346-
print ' okay %s' % fname
348+
logger.debug(' okay %s' % fname)
347349
else:
348-
print ' update %s' % fname
350+
logger.debug(' update %s' % fname)
349351
si_uid = _update_file(c, dir, fname, studies, series, storage_instances)
350352
if fname not in db_mtimes:
351353
query = """INSERT INTO file (directory,
@@ -365,14 +367,14 @@ def _update_file(c, path, fname, studies, series, storage_instances):
365367
try:
366368
do = dicom.read_file('%s/%s' % (path, fname))
367369
except dicom.filereader.InvalidDicomError:
368-
print ' not a DICOM file'
370+
logger.debug(' not a DICOM file')
369371
return None
370372
try:
371373
study_comments = do.StudyComments
372374
except AttributeError:
373375
study_comments = ''
374376
try:
375-
print ' storage instance %s' % str(do.SOPInstanceUID)
377+
logger.debug(' storage instance %s' % str(do.SOPInstanceUID))
376378
if str(do.StudyInstanceUID) not in studies:
377379
query = """INSERT INTO study (uid,
378380
date,
@@ -420,7 +422,7 @@ def _update_file(c, path, fname, studies, series, storage_instances):
420422
c.execute(query, params)
421423
storage_instances.append(str(do.SOPInstanceUID))
422424
except AttributeError, data:
423-
print ' %s' % str(data)
425+
logger.debug(' %s' % str(data))
424426
return None
425427
return str(do.SOPInstanceUID)
426428

@@ -468,13 +470,13 @@ def clear_cache():
468470
def _init_db(verbose=True):
469471
""" Initialize database """
470472
if verbose:
471-
print 'db filename: ' + DB_FNAME
473+
logger.info('db filename: ' + DB_FNAME)
472474
global DB
473475
DB = sqlite3.connect(DB_FNAME, check_same_thread=False)
474476
with _db_change() as c:
475477
c.execute("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'")
476478
if c.fetchone()[0] == 0:
477-
print 'create'
479+
logger.debug('create')
478480
for q in CREATE_QUERIES:
479481
c.execute(q)
480482

0 commit comments

Comments
 (0)