python - 使用 argparse 传递一个目录(不需要类型检查)

标签 python argparse

我已经写了一个文件爬虫,我正在尝试扩展它。我想使用 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/

相关文章:

python - 谷歌静态 map API : representing a route as an encoded polyline

python - 在完全嵌套的 for 循环中返回值

python - argparse 一个参数而不是其他几个参数

python - django-templated-email 不适用于 Heroku

python - 未知符号 matplotlib mathtext

python - 将 argparse 转义字符作为选项处理

python-3.x - 错误 : argument are required -i/--image

python - 参数解析 : How to organize output and how to get str input?

python - 使用 Python 获取 Youtube 数据

python - 如何选择与数据框中某一特定列高度相关的列