0

I wrote a Python script that I am now trying to get to run via the command line. It consists of a function that takes one obligatory and a few optional arguments.

def main(input_folder, iterations = 1000, probability_cutoff = - 40 , threshold = 10): ...

Now I am trying to make it executable through the command line like so:

if __name__ == "__main__": main(sys.argv[1])

This works well as long as I put in only one argument; but I don't know how to accept the additional, optional input that sys.argv delivers as a list.

  • Is there a simple way of doing this with this approach?
  • Or is it necessary to use an additional module such as argparse?
  • I tried feeding keyword arguments into the function as well but couldn't make that work either - is that a feasible approach?

I am working with Python 2.7 on a Mac. Any help is much appreciated!

patrick
  • 4,455
  • 6
  • 44
  • 61
  • I'm going to say this is a duplicate of [How to extract parameters from a list and pass them to a function call](http://stackoverflow.com/questions/7527849/how-to-extract-parameters-from-a-list-and-pass-them-to-a-function-call) because that is the mechanism you are asking for (as well as `[1:]` to skip the first item of argv) – Tadhg McDonald-Jensen May 03 '16 at 14:16
  • that is probably true but I did not find that one as I was not using the right search terms. Should I delete this one? – patrick May 03 '16 at 14:19
  • not at all, anyone else trying to unpack `sys.argv` (like you) but doesn't use the right search terms to find the relevant question (like you) will find this question and it will help them. – Tadhg McDonald-Jensen May 03 '16 at 14:22
  • 1
    I would like to note however that all the elements of `sys.argv` are strings so when you do `main(*sys.argv[1:])` like in the accepted answer you will need to parse the numbers yourself. – Tadhg McDonald-Jensen May 03 '16 at 14:25
  • yes I just added int() to whenever they are used. Is that what you meant? – patrick May 03 '16 at 14:30
  • 1
    yeah, just reminding you since your default values are already integers so any conversions would be redundant (not a problem but you might forget why conversions are needed) – Tadhg McDonald-Jensen May 03 '16 at 14:36
  • 1
    Type conversion is another reason I prefer argparse, @TadhgMcDonald-Jensen. I've added it to the answer. – Don Kirkby May 03 '16 at 14:45

1 Answers1

2

I always use argparse, because it gives you nice error handling, converts strings to ints or open files, and clearly documents the options. However, this should do what you want:

if __name__ == "__main__":
    main(*sys.argv[1:])
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286