1

I am trying to pass arguments of type bool and while running the code I run python main.py --tcpip=False. This does not work for me.

I have tried to change it to type str and it works completely fine.

import argparse
parser = argparse.ArgumentParser(description="SSD and Gender Detection")
parser.add_argument("--tcpip",default = "True",type=str,help='transfer data via tcp/ip')
args = parser.parse_args()
print(args.tcpip)

if __name__ == '__main__':

    if(args.tcpip == "True"):
        send_data(count)

It prints True even when I start the code with python main.py --tcpip=False

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 2
    `"True"` has type `str`. `True` has type `bool`. Just because a quoted string happens to consist of the word T-r-u-e doesn't suddenly cause the type to change from `str` to `bool`. – Tom Karzes Jun 19 '19 at 14:19
  • Yeah, this case is really unintuitive –  Jun 19 '19 at 14:20
  • `type=bool` fails because: `bool("False")` produces `True`. The only string that produces `False` is the empty one, `""`. Your `=="True"` is the right test. – hpaulj Jun 19 '19 at 18:34

1 Answers1

3

You should use the action argument:

    parser.add_argument("--tcpip",action='store_false',help='transfer data via tcp/ip')

Now the value of tcpip is True by default, and when run with the argument --tcpip, the value will change to False.

>>> python main.py
True
>>> python main.py --tcpip
False

Then you can change the condition to:

if args.tcpip:
    send_data(count)

Some more reading - here

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61