Объединение параметров выбора файлов и каталогов - PullRequest
0 голосов
/ 21 марта 2011

Я хотел бы объединить функциональность двух аргументов в один. В настоящее время -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) )

1 Ответ

1 голос
/ 21 марта 2011

Вы можете передать список шаблонов, каталогов и файлов для этой функции.Однако ваша оболочка расширит ваши символы подстановки, если вы не поместите их в кавычки в командной строке.

import os
import glob

def combine(arguments):
    all_files = []
    for arg in arguments:
        if '*' in arg or '?' in arg:
            # contains a wildcard character
            all_files.extend(glob.glob(arg))
        elif os.path.isdir(arg):
            # is a dictionary
            all_files.extend(glob.glob(os.path.join(arg, '*')))
        elif os.path.exists(arg):
            # is a file
            all_files.append(arg)
        else:
            # invalid?
            print '%s invalid' % arg
    return all_files
...