getopt or optparse options/arguments wrapping?

Steven Bethard steven.bethard at
Sun Mar 18 20:45:38 CET 2007

Rocky Zhou wrote:
> .dirs .files is just a snapshot of the current directories, which can
> be used to delete-outdated files when restoring. Here I used absolute
> path by using tar's -P parameter. When fs_rstore, it will do this:
> command = "tar -xpz -P -f %s.tgz -T %s" % (archive, self.t_files)
> maybe I want add some parameters of tar, for example, --strip-path=X,
> so I hope the fs_rstore can do this:
> sh# fs_rstore pages --strip-path=X
> rather than:
> sh# fs_rstore pages -w '--strip-path=X'
> What should I do?

One possibility using argparse ( 
would be to require the '--' pseudo-argument before all tar options. 
Then you could do something like::

     fs_rstore pages -- --strip-path=X --same-owner

That '--' pseudo-argument makes everything else after it into a 
positional argument (even if they start with '-' or '--'), so you can 
then just collect those positional arguments and add them to your 
"command".   Here's what that code might look like::

     >>> parser = argparse.ArgumentParser(prog='fs_backup')
     >>> parser.add_argument('-a', '--append', metavar='[t/x[L]:]PATH')
     >>> parser.add_argument('-d', '--delete', metavar='PATH')
     >>> parser.add_argument('-t', '--type',
     ...                     choices=['full', 'diff', 'incr'])
     >>> parser.add_argument('identity')
     >>> parser.add_argument('tar_options', nargs='*')
     >>> parser.parse_args('-a foo pages -- --strip-path=X')
     >>> args = parser.parse_args(
     ...     '-a foo pages -- --strip-path=X --same-owner'.split())
     >>> args.append
     >>> args.identity
     >>> args.tar_options
     ['--strip-path=X', '--same-owner']
     >>> "tar %s -f %s.tgz" % (' '.join(args.tar_options), args.identity)
     'tar --strip-path=X --same-owner -f pages.tgz'

Note that all the tar options got collected in 'args.tar_options'.

You could get rid of the need for '--' by adding each tar options to 
your parser with an add_argument() call, but I suspect that's too 
tedious. I've added a feature request to argparse to make this kind of 
thing easier::
Not sure when I'll have a chance to look into this though.


P.S. You should be able to get similar behavior out of optparse, though 
you'll have to parse the 'args' list yourself.

More information about the Python-list mailing list