这是我想要实现的目标:
将字符串作为参数传递时,调用 write_text() 函数
python3 app.py 将此文本写入文件
传递虚线参数时,调用另一个函数,在本例中为 read_text()
python3 app.py -r
不传递参数时打印帮助
python3 app.py
这是我到目前为止所拥有的:
parser = argparse.ArgumentParser()
parser.add_argument('text', help="write text to file")
parser.add_argument('-r', '--read', help="read text from file")
args = parser.parse_args()
...
def main():
if args.read:
read_text()
elif args.text:
write_text(args.text)
else:
parser.print_help()
问题是,当我只调用 -r
时,它提示缺少 text
命令,因为 text
不是可选的论证。
我尝试创建子命令并创建所有 args 子命令,但随后需要显式调用 text
参数,如 python3 app.py text
。
我可能对此想得太深,而忽略了一个简单的解决方案。我只是解析 sys.argv 就可以完美地工作,但它并不漂亮。内置的帮助功能也很有用。
提前致谢!
<小时/>编辑:
这是我现在正在使用的内容
parser = argparse.ArgumentParser()
parser.add_argument('text', nargs='*', help="write text to file")
parser.add_argument('-r', '--read', action='store_true', help="read text from file")
args = parser.parse_args()
...
def main():
if args.read:
read_text()
elif args.text:
text = " ".join(args.text)
write_text(text)
else:
parser.print_help()
仍然认为可能有更干净的方法来做到这一点......
最佳答案
这可能有帮助:
parser.add_argument('text', nargs='?', help="write text to file")
更多信息:https://docs.python.org/3/library/argparse.html#nargs
<小时/>请注意,如果您想稍后将 args.read 用作 bool 值,则应使用 action='store_true'
作为 read 参数。
parser.add_argument('-r', '--read', action='store_true', help="read text from file")
关于Python3 argparse : When passing string as arg run funcA, 如果虚线 arg 运行另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60155015/