Adam_G
Adam_G

Reputation: 7879

Python argparse boolean issue

I am having trouble setting a boolean value. My code is:

training_pages_list_file = ''
html_page_dir = ''
clf_file_str = ''
user_idf_param = False

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Classify some CraigsList Pages')
    parser.add_argument('csv_file', action='store')
    parser.add_argument('file_dir', action='store')
    parser.add_argument('clf_file', action='store')
    parser.add_argument('-i', action='store_true', help="include idf", dest=user_idf_param, default=False)
    args = parser.parse_args()

However, this raises:

hon3.4/argparse.py", line 1721, in parse_args
    args, argv = self.parse_known_args(args, namespace)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/argparse.py", line 1742, in parse_known_args
    if not hasattr(namespace, action.dest):
TypeError: hasattr(): attribute name must be string

How can I have it so if -i is included, it will set user_idf_param to True?

Upvotes: 0

Views: 1321

Answers (1)

Navith
Navith

Reputation: 1069

Looks like user_idf_param is supposed to be a name for the attribute that tells you whether or not it was used.

import argparse

training_pages_list_file = ''
html_page_dir = ''
clf_file_str = ''
user_idf_param = "i_param_used"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Classify some CraigsList Pages')
    parser.add_argument('csv_file', action='store')
    parser.add_argument('file_dir', action='store')
    parser.add_argument('clf_file', action='store')
    parser.add_argument('-i', action='store_true', help="include idf", dest=user_idf_param, default=False)

    args = parser.parse_args((...))

    if args.i_param_used:
        ...

Upvotes: 2

Related Questions