我会使用选项回调+帮助器对象来跟踪当前选项的上下文。例子:
from optparse import OptionParser
class FileBase(object):
def __init__(self, fname):
self.fname = fname
self.path = None
class LocalFile(FileBase):
pass
class RemoteFile(FileBase):
pass
class FileOptionParser(object):
def __init__(self):
self.last_file = None
self.files = []
def set_path(self, option, opt, value, parser):
self.last_file.path = value
def set_file(self, option, opt, value, parser):
if option.dest=="local" : cls = LocalFile
elif option.dest=="remote": cls = RemoteFile
else: assert False
self.last_file = cls(value)
self.files.append(self.last_file)
setattr(parser.values, option.dest, self.last_file)
fop = FileOptionParser()
parser = OptionParser()
parser.add_option('-L', '--local', type='string', action='callback', callback=fop.set_file)
parser.add_option('-R', '--remote', type='string', action='callback', callback=fop.set_file)
parser.add_option('-p', '--path', type='string', action='callback', callback=fop.set_path)
(options, args) = parser.parse_args()
print [(f.fname, f.path) for f in fop.files]
例子是:
> python test.py -L local.txt -R remote.txt -p remoteDir/
[('local.txt', None), ('remote.txt', 'remoteDir/')]