0

I'm trying to write a python script that runs from command arguments if the value is not present it should be set to default (or False) and the code should run without failure. here is an example of what I'm trying to perform.

config = sys.argv[1]
val = sys.argv[2]
if (val):
    for i in list:
        print(i)
else:
    print("don't do anything")

I'm running my code like this: python3 test.py config/json TEST=True I want to run the above code if will not provide the TEST value then TEST should be considered False.

any pointer would be really appreciated.

rtk
  • 27
  • 2
  • What happens when you run it as-is? – wwii Sep 02 '22 at 16:29
  • 3
    For this simple example, you could check `len(sys.argv)` to see whether or not a second parameter was passed. As your parameters get more complicated, you're going to want to use a library such as `argparse` that handles all these details for you. – jasonharper Sep 02 '22 at 16:33
  • Could run all your arguments through a function that will set default values depending if the argument was provide or not. Create a function with default values ```def setArgs(configArg, valArg=False):``` then set your variables inside the function to the functions arguments ```config = configArg``` ```val = valArg```. Pass sys arguments to your function like so ```setArgs(*sys.argv[1:])```. If nothing was provided for the second argument, your function automatically sets it to ```False```. – cap1hunna Sep 02 '22 at 16:49
  • You will need to return values from the function in a list and then assign them to your variables. – cap1hunna Sep 02 '22 at 16:58
  • ```import sys``` ```def setArgs(configArg, valArg=False): configa = configArg val = valArg return [configa, val]``` ```configa = setArgs(*sys.argv[1:])[0]``` ```val = setArgs(*sys.argv[1:])[1]``` ```print(configa)``` ```print(val)``` – cap1hunna Sep 02 '22 at 17:01

0 Answers0