14

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
2
  • 4
    Command line arguments are always strings -- the entry point for a C program is specified as int main(int argc, char* argv), and the execv family of syscalls takes arguments as an array of C strings. Since that's how the operating system hands them off, they can't possibly be anything else without being converted, parsed or casted. Commented Dec 6, 2016 at 23:10
  • 3
    You could use argparse(stackoverflow.com/questions/15008758/…) which is a part of the standard library. Among third party libraries Click can be a good option(click.pocoo.org/5/options/#boolean-flags). Commented Dec 6, 2016 at 23:14

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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')

3 Comments

bool does not convert "True" and "False" to True and False. Calling bool on a string is equivalent to len(string) != 0.
Yes, I fixed this.
Suggest to avoid eval, it may have security implications. You may want to use ast.literal_eval() instead.
0

Not sure if may help, what about using argparse?

import argparse

def read_cmdline():
    p=argparse.ArgumentParser()
    p.add_argument("-c","--clear",type=bool, choices=[True,False],required=True)
    args=p.parse_args()
    return args 


if __name__=="__main__":
    args=read_cmdline()
    if args.clear:
        ###actions when clear is True
    else:
        ## actions when clear is False

Note the type=bool in add_argument

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.