我已经写了一个文件爬虫,我正在尝试扩展它。我想使用 argparse 来处理脚本的设置,包括在命令行中传递起始目录。
示例:/var/some/directory/
我有几个其他参数可以工作,但我无法正确传递此目录。我不在乎它前面是否有标志,(例如 -d/path/to/start/
)但我需要确保至少使用了这个参数因为它将是脚本运行的唯一强制选项。
代码示例:
parser = argparse.ArgumentParser(description='py pub crawler...')
parser.add_argument('-v', '--verbose', help='verbose output from crawler', action="store_true")
parser.add_argument('-d', '--dump', help='dumps and replaces existing dictionaries', action="store_true")
parser.add_argument('-f', '--fake', help='crawl only, nothing stored to DB', action="store_true")
args = parser.parse_args()
if args.verbose:
verbose = True
if args.dump:
dump = True
if args.fake:
fake = True
最佳答案
只需添加:
parser.add_argument('directory',help='directory to use',action='store')
在您的 args = parser.parse_args()
行之前。来自命令行的简单测试表明它做了正确的事情(在脚本末尾打印 args
):
$ python test.py /foo/bar/baz
Namespace(directory='/foo/bar/baz', dump=False, fake=False, verbose=False)
$ python test.py
usage: test.py [-h] [-v] [-d] [-f] directory
test.py: error: too few arguments
关于python - 使用 argparse 传递一个目录(不需要类型检查),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15368188/