Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean argument for script

Tags:

python

In Python, I understand how int and str arguments can be added to scripts.

parser=argparse.ArgumentParser(description="""Mydescription""") parser.add_argument('-l', type=str, default='info', help='String argument') parser.add_argument('-dt', type=int, default ='', help='int argument') 

What is it for booleans?

Basically I want to pass a flag into my script which will tell the script whether to do a specific action or not.

like image 277
dublintech Avatar asked Feb 07 '12 21:02

dublintech


People also ask

How do you pass a boolean argument to a Python script?

You can either use the action with store_true | store_false , or you can use an int and let implicit casting check a boolean value. Using the action , you wouldn't pass a --foo=true and --foo=false argument, you would simply include it if it was to be set to true.

What is a boolean argument?

A boolean argument in a function signals exactly the opposite. A flag is used to alter the behaviour of a function based on the context in which it is used. It is a good signal that a function is doing more than one thing and is not cohesive. A flag could cause only a minor change in the logical flow of a function.

How do I pass a boolean to a PowerShell script?

Use Boolean Parameter to Pass Boolean Values to a PowerShell Script From a Command Prompt. You can set the data type of your parameter to [bool] to pass Boolean values to a PowerShell script from a command prompt. Copy param([int]$a, [bool]$b) switch($b){ $true {"It is true."} $false {"It is false."} }

What is boolean in Python with example?

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.


1 Answers

You can either use the action with store_true|store_false, or you can use an int and let implicit casting check a boolean value.

Using the action, you wouldn't pass a --foo=true and --foo=false argument, you would simply include it if it was to be set to true.

python myProgram.py --foo 

In fact I think what you may want is

parser.add_argument('-b', action='store_true', default=False) 
like image 133
sberry Avatar answered Oct 14 '22 23:10

sberry