4114: Would like to use stdin and stdout for command line import/export by MD Nauta

svn: r16308
This commit is contained in:
Doug Blank 2010-12-23 17:47:01 +00:00
parent 3833ee63a6
commit 217316ccf5
3 changed files with 97 additions and 84 deletions

View File

@ -97,9 +97,9 @@ class ArgHandler(object):
else: else:
# Need to convert to system file encoding before printing # Need to convert to system file encoding before printing
# For non latin characters in path/file/user names # For non latin characters in path/file/user names
print msg1.encode(sys.getfilesystemencoding()) print >> sys.stderr, msg1.encode(sys.getfilesystemencoding())
if msg2 is not None: if msg2 is not None:
print msg2.encode(sys.getfilesystemencoding()) print >> sys.stderr, msg2.encode(sys.getfilesystemencoding())
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# Argument parser: sorts out given arguments # Argument parser: sorts out given arguments
@ -145,7 +145,7 @@ class ArgHandler(object):
value = Utils.get_unicode_path_from_env_var(value) value = Utils.get_unicode_path_from_env_var(value)
fname = value fname = value
fullpath = os.path.abspath(os.path.expanduser(fname)) fullpath = os.path.abspath(os.path.expanduser(fname))
if not os.path.exists(fullpath): if fname != '-' and not os.path.exists(fullpath):
self.__error(_('Error: Import file %s not found.') % fname) self.__error(_('Error: Import file %s not found.') % fname)
sys.exit(0) sys.exit(0)
@ -181,20 +181,23 @@ class ArgHandler(object):
# For non latin characters in Windows path/file/user names # For non latin characters in Windows path/file/user names
value = Utils.get_unicode_path_from_env_var(value) value = Utils.get_unicode_path_from_env_var(value)
fname = value fname = value
fullpath = os.path.abspath(os.path.expanduser(fname)) if fname == '-':
if os.path.exists(fullpath): fullpath = '-'
self.__error(_("WARNING: Output file already exists!\n" else:
"WARNING: It will be overwritten:\n %(name)s") % \ fullpath = os.path.abspath(os.path.expanduser(fname))
{'name' : fullpath}) if os.path.exists(fullpath):
answer = None self.__error(_("WARNING: Output file already exists!\n"
while not answer: "WARNING: It will be overwritten:\n %(name)s") % \
answer = raw_input(_('OK to overwrite? (yes/no) ') \ {'name' : fullpath})
.encode(sys.getfilesystemencoding())) answer = None
if answer.upper() in ('Y', 'YES', _('YES').upper()): while not answer:
self.__error( _("Will overwrite the existing file: %s") answer = raw_input(_('OK to overwrite? (yes/no) ') \
% fullpath) .encode(sys.getfilesystemencoding()))
else: if answer.upper() in ('Y', 'YES', _('YES').upper()):
sys.exit(0) self.__error( _("Will overwrite the existing file: %s")
% fullpath)
else:
sys.exit(0)
if family_tree_format is None: if family_tree_format is None:
# Guess the file format based on the file extension. # Guess the file format based on the file extension.
@ -317,9 +320,9 @@ class ArgHandler(object):
self.__import_action() self.__import_action()
for (action, options_str) in self.actions: for (action, options_str) in self.actions:
print "Performing action: %s." % action print >> sys.stderr, "Performing action: %s." % action
if options_str: if options_str:
print "Using options string: %s" % options_str print >> sys.stderr, "Using options string: %s" % options_str
self.cl_action(action, options_str) self.cl_action(action, options_str)
for expt in self.exports: for expt in self.exports:
@ -327,16 +330,16 @@ class ArgHandler(object):
# For non latin characters in Windows path/file/user names # For non latin characters in Windows path/file/user names
fn = expt[0].encode(sys.getfilesystemencoding()) fn = expt[0].encode(sys.getfilesystemencoding())
fmt = str(expt[1]) fmt = str(expt[1])
print "Exporting: file %s, format %s." % (fn, fmt) print >> sys.stderr, "Exporting: file %s, format %s." % (fn, fmt)
self.cl_export(expt[0], expt[1]) self.cl_export(expt[0], expt[1])
if cleanup: if cleanup:
self.cleanup() self.cleanup()
print "Exiting." print >> sys.stderr, "Exiting."
sys.exit(0) sys.exit(0)
def cleanup(self): def cleanup(self):
print "Cleaning up." print >> sys.stderr, "Cleaning up."
# remove files in import db subdir after use # remove files in import db subdir after use
self.dbstate.db.close() self.dbstate.db.close()
if self.imp_db_path: if self.imp_db_path:
@ -366,16 +369,16 @@ class ArgHandler(object):
try: try:
self.sm.open_activate(self.imp_db_path) self.sm.open_activate(self.imp_db_path)
print "Created empty family tree successfully" print >> sys.stderr, "Created empty family tree successfully"
except: except:
print "Error opening the file." print >> sys.stderr, "Error opening the file."
print "Exiting..." print >> sys.stderr, "Exiting..."
sys.exit(0) sys.exit(0)
for imp in self.imports: for imp in self.imports:
fn = imp[0].encode(sys.getfilesystemencoding()) fn = imp[0].encode(sys.getfilesystemencoding())
fmt = str(imp[1]) fmt = str(imp[1])
print "Importing: file %s, format %s." % (fn, fmt) print >> sys.stderr, "Importing: file %s, format %s." % (fn, fmt)
self.cl_import(imp[0], imp[1]) self.cl_import(imp[0], imp[1])
def __open_action(self): def __open_action(self):
@ -391,10 +394,10 @@ class ArgHandler(object):
# we load this file for use # we load this file for use
try: try:
self.sm.open_activate(self.open) self.sm.open_activate(self.open)
print "Opened successfully!" print >> sys.stderr, "Opened successfully!"
except: except:
print "Error opening the file." print >> sys.stderr, "Error opening the file."
print "Exiting..." print >> sys.stderr, "Exiting..."
sys.exit(0) sys.exit(0)
def check_db(self, dbpath, force_unlock = False): def check_db(self, dbpath, force_unlock = False):
@ -466,7 +469,7 @@ class ArgHandler(object):
for chunk in options_str.split(',') ] ) for chunk in options_str.split(',') ] )
except: except:
options_str_dict = {} options_str_dict = {}
print "Ignoring invalid options string." print >> sys.stderr, "Ignoring invalid options string."
name = options_str_dict.pop('name', None) name = options_str_dict.pop('name', None)
_cl_list = pmgr.get_reg_reports(gui=False) _cl_list = pmgr.get_reg_reports(gui=False)
@ -493,15 +496,16 @@ class ArgHandler(object):
else: else:
msg = "Report name not given. Please use one of [-p|--options] name=reportname." msg = "Report name not given. Please use one of [-p|--options] name=reportname."
print "%s\n Available names are:" % msg print >> sys.stderr, "%s\n Available names are:" % msg
for pdata in _cl_list: for pdata in _cl_list:
# Print cli report name ([item[0]) and GUI report name (item[4]) # Print cli report name ([item[0]) and GUI report name (item[4])
if len(pdata.id) <= 25: if len(pdata.id) <= 25:
print " %s%s- %s" % ( pdata.id, print >> sys.stderr, \
" " * (26 - len(pdata.id)), " %s%s- %s" % ( pdata.id, " " * (26 - len(pdata.id)),
pdata.name.encode(sys.getfilesystemencoding())) pdata.name.encode(sys.getfilesystemencoding()))
else: else:
print " %s\t- %s" % (pdata.id, pdata.name.encode(sys.getfilesystemencoding())) print >> sys.stderr, " %s\t- %s" % (pdata.id,
pdata.name.encode(sys.getfilesystemencoding()))
elif action == "tool": elif action == "tool":
from gui.plug import tool from gui.plug import tool
@ -510,7 +514,7 @@ class ArgHandler(object):
chunk in options_str.split(',') ] ) chunk in options_str.split(',') ] )
except: except:
options_str_dict = {} options_str_dict = {}
print "Ignoring invalid options string." print >> sys.stderr, "Ignoring invalid options string."
name = options_str_dict.pop('name', None) name = options_str_dict.pop('name', None)
_cli_tool_list = pmgr.get_reg_tools(gui=False) _cli_tool_list = pmgr.get_reg_tools(gui=False)
@ -531,15 +535,16 @@ class ArgHandler(object):
else: else:
msg = "Tool name not given. Please use one of [-p|--options] name=toolname." msg = "Tool name not given. Please use one of [-p|--options] name=toolname."
print "%s\n Available names are:" % msg print >> sys.stderr, "%s\n Available names are:" % msg
for pdata in _cli_tool_list: for pdata in _cli_tool_list:
# Print cli report name ([item[0]) and GUI report name (item[4]) # Print cli report name ([item[0]) and GUI report name (item[4])
if len(pdata.id) <= 25: if len(pdata.id) <= 25:
print " %s%s- %s" % ( pdata.id, print >> sys.stderr, \
" " * (26 - len(pdata.id)), " %s%s- %s" % ( pdata.id, " " * (26 - len(pdata.id)),
pdata.name.encode(sys.getfilesystemencoding())) pdata.name.encode(sys.getfilesystemencoding()))
else: else:
print " %s\t- %s" % (pdata.id, pdata.name.encode(sys.getfilesystemencoding())) print >> sys.stderr, " %s\t- %s" % (pdata.id,
pdata.name.encode(sys.getfilesystemencoding()))
else: else:
print "Unknown action: %s." % action print >> sys.stderr, "Unknown action: %s." % action
sys.exit(0) sys.exit(0)

View File

@ -231,7 +231,7 @@ class ArgParser(object):
# if there were an argument without option, # if there were an argument without option,
# use it as a file to open and return # use it as a file to open and return
self.open_gui = leftargs[0] self.open_gui = leftargs[0]
print "Trying to open: %s ..." % leftargs[0] print >> sys.stderr, "Trying to open: %s ..." % leftargs[0]
#see if force open is on #see if force open is on
for opt_ix in range(len(options)): for opt_ix in range(len(options)):
option, value = options[opt_ix] option, value = options[opt_ix]
@ -262,7 +262,7 @@ class ArgParser(object):
elif option in ( '-a', '--action' ): elif option in ( '-a', '--action' ):
action = value action = value
if action not in ( 'report', 'tool' ): if action not in ( 'report', 'tool' ):
print "Unknown action: %s. Ignoring." % action print >> sys.stderr, "Unknown action: %s. Ignoring." % action
continue continue
options_str = "" options_str = ""
if opt_ix < len(options)-1 \ if opt_ix < len(options)-1 \
@ -270,7 +270,7 @@ class ArgParser(object):
options_str = options[opt_ix+1][1] options_str = options[opt_ix+1][1]
self.actions.append((action, options_str)) self.actions.append((action, options_str))
elif option in ('-d', '--debug'): elif option in ('-d', '--debug'):
print 'setup debugging', value print >> sys.stderr, 'setup debugging', value
logger = logging.getLogger(value) logger = logging.getLogger(value)
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
cleandbg += [opt_ix] cleandbg += [opt_ix]
@ -287,20 +287,22 @@ class ArgParser(object):
set_value = True set_value = True
if config.has_default(setting_name): if config.has_default(setting_name):
setting_value = config.get(setting_name) setting_value = config.get(setting_name)
print "Current Gramps config setting: %s:%s" % ( print >> sys.stderr, "Current Gramps config setting: " \
setting_name, repr(setting_value)) "%s:%s" % (setting_name, repr(setting_value))
if set_value: if set_value:
if new_value == "DEFAULT": if new_value == "DEFAULT":
new_value = config.get_default(setting_name) new_value = config.get_default(setting_name)
else: else:
new_value = safe_eval(new_value) new_value = safe_eval(new_value)
config.set(setting_name, new_value) config.set(setting_name, new_value)
print " New Gramps config setting: %s:%s" % ( print >> sys.stderr, " New Gramps config " \
setting_name, repr(config.get(setting_name))) "setting: %s:%s" % (setting_name, \
repr(config.get(setting_name)))
else: else:
need_to_quit = True need_to_quit = True
else: else:
print "Gramps: no such config setting: '%s'" % setting_name print >> sys.stderr, "Gramps: no such config setting:" \
" '%s'" % setting_name
need_to_quit = True need_to_quit = True
else: else:
print "Gramps config settings from %s:" % \ print "Gramps config settings from %s:" % \

View File

@ -125,46 +125,52 @@ class GrampsXmlWriter(UpdateCallback):
""" """
Write the database to the specified file. Write the database to the specified file.
""" """
base = os.path.dirname(filename) if filename == '-':
if os.path.isdir(base): import sys
if not os.access(base, os.W_OK) or not os.access(base, os.R_OK): g = sys.stdout
raise DbWriteFailure( self.compress = False
_('Failure writing %s') % filename, else:
_("The database cannot be saved because you do " base = os.path.dirname(filename)
"not have permission to write to the directory. " if os.path.isdir(base):
"Please make sure you have write access to the " if not os.access(base, os.W_OK) or not os.access(base, os.R_OK):
"directory and try again.")) raise DbWriteFailure(
return 0 _('Failure writing %s') % filename,
_("The database cannot be saved because you do "
if os.path.exists(filename): "not have permission to write to the directory. "
if not os.access(filename, os.W_OK): "Please make sure you have write access to the "
raise DbWriteFailure( "directory and try again."))
_('Failure writing %s') % filename, return 0
_("The database cannot be saved because you do "
"not have permission to write to the file. " if os.path.exists(filename):
"Please make sure you have write access to the " if not os.access(filename, os.W_OK):
"file and try again.")) raise DbWriteFailure(
return 0 _('Failure writing %s') % filename,
_("The database cannot be saved because you do "
"not have permission to write to the file. "
"Please make sure you have write access to the "
"file and try again."))
return 0
self.fileroot = os.path.dirname(filename) self.fileroot = os.path.dirname(filename)
try: try:
if self.compress and _gzip_ok: if self.compress and _gzip_ok:
try: try:
g = gzip.open(filename,"wb") g = gzip.open(filename,"wb")
except: except:
g = open(filename,"w")
else:
g = open(filename,"w") g = open(filename,"w")
else: except IOError,msg:
g = open(filename,"w") LOG.warn(str(msg))
except IOError,msg: raise DbWriteFailure((_('Failure writing %s') % filename,
LOG.warn(str(msg)) str(msg)))
raise DbWriteFailure((_('Failure writing %s') % filename, return 0
str(msg)))
return 0
self.g = codecs.getwriter("utf8")(g) self.g = codecs.getwriter("utf8")(g)
self.write_xml_data() self.write_xml_data()
g.close() if filename != '-':
g.close()
return 1 return 1
def write_handle(self, handle): def write_handle(self, handle):