-1

I am fairly new to Python. I need a piece of code to run when either (i) No command line arguments are passed (ii) A particular command line argument, say "help", is passed

I have tried working with argparse and sys but I can't seem to get both to work.

For the argparse, I tried "default='help'" while adding the argument: parser=add_argument("arg1",default="help")

For the sys.argv, I tried the following code:

if (sys.argv[1] == 'help') or not (len(sys.argv) > 1)

But this just gave me an "Index out of range" error.

ZarryMyles
  • 23
  • 6
  • 1
    What happens when you fix the indentation error? – MattDMo Dec 17 '20 at 20:19
  • Maybe this will help you https://stackoverflow.com/questions/45621722/im-getting-an-indentationerror-how-do-i-fix-it https://stackoverflow.com/questions/24342636/indentation-errors-in-python https://stackoverflow.com/questions/14979224/indentation-error-in-python – tibi Dec 17 '20 at 20:23
  • An indentation error is a python syntax one. You have even gotten to the point of running the code. Fix the indentation first (that's basic Python). – hpaulj Dec 17 '20 at 21:14
  • If you are new to Python, don't try to do fancy things with the inputs. Use straightforward `argparse` arguments. And make sure you do a `print(args)` to see exactly what the parser has done. – hpaulj Dec 18 '20 at 00:45
  • I forgot to mention this in the question but since I am not passing any arguments in, there is no sys.argv[1]. Hence, I get a `list index out of range` error. Not an indentation error. My bad. I'm sorry about that. – ZarryMyles Dec 18 '20 at 10:51

1 Answers1

0
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--arg1", default="help")
args = parser.parse_args()

def help():
    print("I'm here to help, sorta")

if args.arg1 == "help":
    help()

Running this without any command line arguments will output the help message. Running this with python3 program.py --arg1 help (assuming this code is in the file program.py) will also output the help message. Finally, running python3 program.py --arg1 nohelp will not output the help message (not just 'nohelp', but anything other than 'help').

Martin
  • 1,095
  • 9
  • 14