Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write boolean command line arguments with Python?

Tags:

python

I would like to write an argument in an application where the argument that I am calling needs to be referenced on the first iteration/run of the script where the initial_run is set to True. Otherwise this value should be left as false. Now this parameter is configured in a configuration file.

The current code that I written is below. What should be changed in this code to return the True value? Now it only returns the value False.

import sys  
# main
param_1= sys.argv[0:] in (True, False)
print 'initial_run=', param_1
like image 711
gwestdev1 Avatar asked Dec 06 '16 23:12

gwestdev1


People also ask

How do you pass a boolean in a command line argument in Python?

import argparse parser = argparse. ArgumentParser(description="Parse bool") parser. add_argument("--do-something", default=False, action="store_true", help="Flag to do something") args = parser. parse_args() if args.

How do you write a Boolean expression in Python?

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 .

How do you assign a boolean value to a variable in Python?

Evaluate Variables and Expressions We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.

Can you add Booleans in Python?

In Python, True == 1 and False == 0 , as True and False are type bool , which is a subtype of int . When you use the operator + , it is implicitly adding the integer values of True and False .


2 Answers

Running the script from the command line:

# ./my_script.py true

The boolean can be obtined by doing:

import sys

initial_run = sys.argv[1].lower() == 'true'

This way we are doing a comparison of the first argument lowercased to be 'true', and the comparison will return boolean True if the strings match or boolean False if not.

like image 168
Dalvenjia Avatar answered Oct 21 '22 22:10

Dalvenjia


change

param_1 = sys.argv[0:] in (True, False)

to:

param_1 = eval(sys.argv[1])
assert isinstance(param_1, bool), raise TypeError('param should be a bool')
like image 33
Thmei Esi Avatar answered Oct 22 '22 00:10

Thmei Esi