我有两个功能,(1)运行演示分析,(2)通过文件读取的自定义功能。我想传递一个命令行参数供用户选择演示功能或自定义功能为true或false。无需传递其他任何值。我不确定应该在函数中添加什么以接受arg.parse
def demo()
print("This is demo function")
def custom()
print("This is custom function")
def main():
parser = argparse.ArgumentParser(description="Argument Parser is boolean to run Pipeline'")
parser.add_argument("--demo", help='Demo data to show an example')
parser.add_argument("--custom", help='Specify custom analysis, sql query is read from userquery.sql')
args = parser.parse_args()
if args.demo == True:
demoanalysis()
elif args.custom == True:
customanalysis()
else:
print("Don't do anything")
但是,当我运行脚本时,它会直接转到第三个选项。
python script.py --demo True --custom False
Don't do anything
我知道需要将某些内容传递给每个函数以接受布尔参数,但不确定如何执行。有什么建议么。谢谢。
答案 0 :(得分:0)
我想,您可以使用action="store_true"
自变量(在docs中更多):
def main():
parser = argparse.ArgumentParser(description="Argument Parser is boolean to run Pipeline'")
parser.add_argument("--demo", action="store_true", help='Demo data to show an example')
parser.add_argument("--custom", action="store_true", help='Specify custom analysis, sql query is read from userquery.sql')
args = parser.parse_args()
if args.demo: # need no comparison with True, because demo is True or False itself
demoanalysis()
elif args.custom:
customanalysis()
else:
print("Don't do anything")
编辑:如果命令行参数中没有关键字,则store_true
默认创建False
值。
用法示例:
python demo_script.py --demo # prints "This is demo function"
python demo_script.py --custom # prints "This is custom function"
希望有帮助!
答案 1 :(得分:0)
您还可以构建一个函数来检查传递给该函数的参数是否有效:
def main():
parser = argparse.ArgumentParser(description="Argument Parser is boolean to run Pipeline'")
# Here you add a type definition to your arguments
parser.register('type', 'bool', (lambda x: str(x).lower() == "true") )
parser.add_argument("--demo", type="bool", help='Demo data to show an example')
parser.add_argument("--custom", type="bool", help='Specify custom analysis, sql query is read from userquery.sql')
args = parser.parse_args()
if args.demo:
demoanalysis()
elif args.custom:
customanalysis()
else:
print("Don't do anything")