在我编写的脚本中,我使用argparse作为主要参数(for--help,--todo等),但是尝试使用系统argv获取作为--add的第三个参数指定的文件名。我用的是:
def parseargs():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--help", help="Print argument usage", action="store_true")
parser.add_argument("--memo", help="Read memo file", action="store_true")
parser.add_argument("--todo", help="Read TODO file", action="store_true")
parser.add_argument("--trackedfiles", help="Read tracked files list", action="store_true")
parser.add_argument("--add", help="Add a file to trackedfiles", action="store_true")
parser.add_argument("--edit", help="Edit file in .wpm_data with editor", action="store_true")
parser.add_argument("--newdir", help="Create a new directory to initialize user-data", action="store_true")
parser.add_argument("file")
p_args = parser.parse_args()
if p_args.help:
printargs()
sys.exit()
if p_args.memo:
print_memo()
sys.exit()
if p_args.todo:
print_todo()
sys.exit()
if p_args.trackedfiles:
print_trackedfiles()
sys.exit()
if p_args.add: # this is were I'm stumpped
if p_args.file == sys.argv[2]:
givenfile = p_args.file
else:
pass
print("[!]\t", givenfile, "to be added to trackedfiles")
sys.exit()
工作原理如下:
^{pr2}$但是当使用不同的参数时,如--help
,则需要对givenfile使用第三个参数
./main.py --help
usage: main.py [--help] [--memo] [--todo] [--trackedfiles] [--add] [--edit]
[--newdir]
file
main.py: error: the following arguments are required: file
如何使用argparse和系统argv,与系统argv不需要经常使用,所以只有在需要它的函数运行时才能调用它?在
你做错了。下面是一些可以帮助您理解如何使用argparse的示例。这些标志不是布尔值,它们可以有值。在
下面是用法。在
^{pr2}$我希望这有帮助。在
我想知道你想做什么,但我的建议是:
因此,最大的变化是使“filename”成为“add”或“edit”标志的参数,而不是位置参数。如果它是一个必需的位置参数,如果用
memo
这样的参数来忽略它,则会收到一条错误消息。在或者,
file
可以是nargs='?'
位置。在您也可以将其设置为一个subparsers情况,其中
memo,todo,trackfiles,add,etc
都是“commands”。其中一些人会接受“文件”论点,其他人则不会。我想其他人会详细说明这一点。在How do I check for a particular subparser? 有一个好的
subparsers
答案。在一种非次级方案:
^{pr2}$这应该接受
prog.py memo
,prog.py add myfile
这样的命令。add_file(afilename)
如果参数是None
或文件名错误,则应该执行智能操作。在如果您想在每次调用中接受多个“命令”,那么我们需要进行一些更改。在
相关问题 更多 >
编程相关推荐