Thursday, March 31, 2022

Python argparse command line flags without arguments

 import argparse

parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-skip', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.


parser.add_argument('-foo', action='store_const', const=42)
args = parser.parse_args()
print(args.skip)
print(args.foo)

Execution :
python myparser.py
>> False
>> None
python myparser.py -skip
>> True
>> None
python myparser.py -skip -foo
>> True
>>42
python myparser.py -foo
>> False

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...