0

So I have my main.py script which essentially will run certain conditional statements based on what is passed on the command-line. For example , if I use main.py -t, this will run test mode. If I run main.py -j /testdata -c 2222-22-22 -p 2222-22-22 this will run default mode and so on.

How can I stop passing in the flags on command line and be able to run my code, so rather than using the flags -j , -c and -p , I can just pass the values normally .

My code is as follows so far :

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--execute-cur-date", action="store", required=False)
    parser.add_argument("-p", "--execute-pre-date", action="store", required=False)
    parser.add_argument("-j", "--execute-json-path", action="store", required=False)
    parser.add_argument("-t", "--execute-test", action="store_true", required=False)
    args = parser.parse_args()

    if args.execute_test:

        testing()

    elif args.execute_json_path and args.execute_cur_date and args.execute_pre_date:
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30
  • 1
    `argparse` accepts `positional` arguments, ones that depend entirely on position (order) rather than flags. But with those you have to provide all values, in the order defined by parser. Or you could just parse the `sys.argv` list yourself. – hpaulj Jan 23 '19 at 09:01
  • @hpaulj How will it know which conditional statements to mean with sys.argv ? – junior_py tester Jan 23 '19 at 09:14
  • In `sys.argv` you just get a list of strings, and your own code has to decide which means what. Stick with the flagged version if that confuses you, – hpaulj Jan 23 '19 at 09:20
  • You are getting unhelpful answers because your question does not make any sense. What do you mean "pass the values normally"? User @ arudzinska seems to have provided the most cogent answer. Why are you parsing the command line for arguments other than `-t` if you aren't doing anything when those flags are present? – Kurtis Rader Jan 24 '19 at 05:19

2 Answers2

1

Use the sys module to parse the command line arguments (sys.argv will be a list of the arguments):

#!/usr/bin/env python3

import sys

# The first argument (sys.argv[0]) is the script name
print('Command line arguments:', str(sys.argv))

Running the script:

$ python3 script.py these are my arguments
Command line arguments: ['script.py', 'these', 'are', 'my', 'arguments']

You can find more examples of usage in this tutorial.

arudzinska
  • 3,152
  • 1
  • 16
  • 29
  • so if i use sys.argv , how it differentiate between the conditional statements ? – junior_py tester Jan 23 '19 at 09:11
  • They are stored in a list and you can check them individually – offeltoffel Jan 23 '19 at 09:12
  • If you don't want to use flags, then your arguments will need to have a specific order - you will retrieve them from the argument list based on their position. You will need to write the logic of processing each argument in the conditional statements. – arudzinska Jan 23 '19 at 09:14
  • @arudzinska Could you point to or provide an example. I am a little confused ? – junior_py tester Jan 23 '19 at 09:17
  • For example, you can check the length of the arguments list and if it is equal to 1 (only the script name) then it means that no arguments were passed and you can run in the standard mode. If length of the arguments list is bigger than 1, then it means that some arguments were passed (`sys.argv[1:]`), so you probably should validate them and then run some other instructions in your script. Check out [this question](https://stackoverflow.com/questions/9442313/can-sys-argv-handle-optional-arguments). – arudzinska Jan 23 '19 at 09:23
  • @arudzinska That make some sense. However , when i do the following: python main.py /Users/yasserkhan/Documents/data-code/Testdata I get the error saying : main.py: error: unrecognized arguments: /Users/yasserkhan/Documents/data-code/Testdata if i get rid of the conditional statement if args.execute_test: then it will work – junior_py tester Jan 23 '19 at 09:43
  • It's hard to say, because we don't see your current code, but that looks like an `argparse` module error. If you decide to stick to `sys.argv` then you need to rewrite your code removing the old argparse parts. – arudzinska Jan 23 '19 at 09:48
1

You may want to take a look at python-fire https://github.com/google/python-fire

import fire


def main(c=None, p=None, j=None, t=None):
    print(c, p, j, t)
    if c:
        print("C passed")
    elif p and j and t:
        print("P, J, T passed")


if __name__ == "__main__":
    fire.Fire(main)

you can just pass None to skip param.

python main.py None p_val j_val t_val

python main.py c_val

Dushyant
  • 21
  • 1
  • 6