简体   繁体   English

命令行参数后跟argparse选项

[英]command line argument followed by argparse option

I'm new to python and currently playing around with argpase. 我是python的新手,目前正在使用argpase。 I'm trying to call a function using a directory path given as a command line argument followed by an argparse option(-name) and a regex that goes through all the files in the directory and spits out all the matches to the regex as so: 我试图使用给定的目录路径作为命令行参数来调用函数,后跟一个argparse选项(-name)和一个正则表达式,该正则表达式会遍历该目录中的所有文件,从而将所有与正则表达式匹配的内容吐出来:

./find.py ../seek -name '[az]*\\.txt'

However, I'm getting a error that looks like 但是,我收到一个看起来像的错误

usage: find.py [-h] [--path PATH] [-name] [--regex REGEX] find.py: error: unrecognized arguments: . . / seek / program . c

And without the -name its just printing all the files inside the path. 如果没有-name,则只打印路径中的所有文件。

Here is what I have so far: 这是我到目前为止的内容:

#!/usr/bin/python2.7

import os, sys, argparse,re 
from stat import *

def parse(argv=None):
   parser = argparse.ArgumentParser()
   parser.add_argument('--path', help='path of directory', action='store')
   parser.add_argument('-name', '--name', action='store_true')
   parser.add_argument('--regex', default=r"[a-z0-9A-Z]")
   args = parser.parse_args(argv)
   print(args)
   return args

def main(argv=None):

   direc = sys.argv[1]
   files = []

   for f in os.listdir(direc):
      pathname = os.path.join(direc, f)
      mode = os.stat(pathname).st_mode

      if S_ISREG(mode):  
         args = parse(pathname)      
         if args.name:  
            dirls = [re.match(args.regex, pathname)]
            print(dirls)
         else:
            print pathname

if __name__ == '__main__':main() 

Any thoughts? 有什么想法吗?

In order for your program to operate, you need a path. 为了使程序运行,您需要一个路径。 So, the --path option must take an argument. 因此,-- --path选项必须带有一个参数。 Modify your parse() function to change the line 修改您的parse()函数以更改行

parser.add_argument('--path', help='path of directory', action='store')

to

parser.add_argument('--path', help='path of directory', action='store', required=True)

You need to call parse_args() only once. 您只需要调用一次parse_args() Remove the parse() invocation to the top of the loop. parse()调用删除到循环的顶部。

And you needn't do 而且你不需要

direc = sys.argv[1]

if you are using argparse . 如果您使用的是argparse

re.match() returns a match object , which is probably not what you want to print. re.match()返回一个match对象 ,可能不是您要打印的对象。

You might want to take a look at match() versus search() . 您可能想看看match()search()

The match() function only checks if the RE matches at the beginning of the string while search() will scan forward through the string for a match. match()函数仅检查RE是否在字符串开头匹配,而search()将向前search()字符串以查找匹配项。

If you wanted to print the file names matching the regex, you could do 如果要打印与正则表达式匹配的文件名,则可以执行

  if S_ISREG(mode):  
     #args = parse(pathname)      
     if args.name:  
        #dirls = re.match(args.regex, pathname)
        dirls = re.search(args.regex, pathname)
        if( dirls ):
           print(pathname)
     else:
        print pathname

So main() should be something like 所以main()应该像

def main(argv=None):
    args = parse(sys.argv[1:])
    print(args)
    #direc = sys.argv[1]
    direc = args.path
    files = []

    for f in os.listdir(direc):
      pathname = os.path.join(direc, f)
      mode = os.stat(pathname).st_mode

    if S_ISREG(mode):  
       #args = parse(pathname)      
       if args.name:  
          #dirls = re.match(args.regex, pathname)
          dirls = re.search(args.regex, pathname)
          if( dirls ):
             print(pathname)
       else:
          print pathname

In order to specify the regex matching the file names, you must specify the regex using the --regex option. 为了指定与文件名匹配的正则表达式,必须使用--regex选项指定正则表达式。 By default, you've made it to match names having only numbers and (English) letters. 默认情况下,您已使其匹配仅包含数字和(英文)字母的名称。

./find.py --path ../seek -name --regex [a-z]\*.txt

or 要么

./find.py --path ../seek -name --regex '[a-z]*.txt'

Argument Parser PATH Example : Different type of arguments with custom handlers added. 参数解析器PATH示例 :添加了自定义处理程序的不同类型的参数。 For path here you can pass '-path' followed by path value as argument 对于此处的路径,您可以传递“ -path”,后跟路径值作为参数

import os
import argparse
from datetime import datetime


def parse_arguments():
    parser = argparse.ArgumentParser(description='Process command line arguments.')
    parser.add_argument('-path', type=dir_path)
    parser.add_argument('-e', '--yearly', nargs = '*', help='yearly date', type=date_year)
    parser.add_argument('-a', '--monthly', nargs = '*',help='monthly date', type=date_month)

    return parser.parse_args()


def dir_path(path):
    if os.path.isdir(path):
    return path
    else:
    raise argparse.ArgumentTypeError(f"readable_dir:{path} is not a valid path")


def date_year(date):
    if not date:
    return

    try:
    return datetime.strptime(date, '%Y')
    except ValueError:
    raise argparse.ArgumentTypeError(f"Given Date({date}) not valid")


def date_month(date):
    if not date:
    return

    try:
    return datetime.strptime(date, '%Y/%m')
    except ValueError:
    raise argparse.ArgumentTypeError(f"Given Date({date}) not valid")


def main():
    parsed_args = parse_arguments()

if __name__ == "__main__":
main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM