【问题标题】:Combining file and directory selection options结合文件和目录选择选项
【发布时间】: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


【解决方案1】:

您可以将通配符、目录和文件的列表传递给此函数。但是,如果您不在命令行中将通配符放在引号之间,您的 shell 会扩展通配符。

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

【讨论】:

  • 目前我不必使用带通配符的引号,这是函数或通配符的限制吗?
  • @Astron - 我的函数接受来自用户的选项列表/元组,因此您可以使用combine(options.filename) 调用它。在shell中,如果你做python yourScript.py *.txt,它不会收到字符串*.txt,而是你当前目录下的文件列表,比如a.txt b.txt c.txt
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 2016-03-17
相关资源
最近更新 更多