【发布时间】:2011-03-21 16:02:55
【问题描述】:
我想将两个参数的功能合二为一。目前 -f 可用于指定单个文件或通配符,-d 可指定目录。我希望 -f 处理它当前的功能或目录。
这是当前的选项语句:
parser.add_option('-d', '--directory',
action='store', dest='directory',
default=None, help='specify directory')
parser.add_option('-f', '--file',
action='store', dest='filename',
default=None, help='specify file or wildcard')
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
(options, args) = parser.parse_args()
这是功能中的逻辑,这些可以组合吗?
filenames_or_wildcards = []
# remove next line if you do not want allow to run the script without the -f -d
# option, but with arguments
filenames_or_wildcards = args # take all filenames passed in the command line
# if -f was specified add them (in current working directory)
if options.filename is not None:
filenames_or_wildcards.append(options.filename)
# if -d was specified or nothing at all add files from dir
if options.directory is not None:
filenames_or_wildcards.append( os.path.join(options.directory, "*") )
# Now expand all wildcards
# glob.glob transforms a filename or a wildcard in a list of all matches
# a non existing filename will be 'dropped'
all_files = []
for filename_or_wildcard in filenames_or_wildcards:
all_files.extend( glob.glob(filename_or_wildcard) )
【问题讨论】:
-
“这些可以合并吗”?您是在问如何组合不同的代码行——不同的代码行?
-
@S.Lott:我在问如何组合文件名和目录指令。
标签: python function scripting arguments options