0

My command line script takes several arguments including strings, ints, floats and lists, and it is becoming a bit tricky to do the call with all arguments:

python myscript.py arg1 arg2 arg3 ... argN

To avoid having to write all arguments in the command line I have created a text file with all arguments which I simply read line by line to collect arguments. This is working fine, but is this the best practice for doing this? Are there a more effective way?

LukeBowl
  • 200
  • 2
  • 13
  • 1
    `argparse` is pretty great in that it lets you put commandline arguments in a file and read from there which is useful when the number of parameters start to get unwieldy... But if you have lots of things that you want to change, you're probably better off using some sort of structured initialization file (e.g. `configparser`) – mgilson Aug 31 '16 at 08:10
  • 1
    It really depends on usage. If a user has to type those parameters in each time then a file might be less error-prone. If the parameters don't change very often, then you could use environment variables, but that can be messy so I don't recommend that. You could read from `stdin` and then either pipe the values in or use a here document (a shell device for passing embedded data). Could you clarify how the program is being called, i.e. from the command-line or a script? – cdarke Aug 31 '16 at 08:11
  • @cdarke Now I call the program by `python myscript.py input_args.txt` with the text file containing my arguments – LukeBowl Aug 31 '16 at 08:15
  • 1
    Duplicate of http://stackoverflow.com/questions/1009860/command-line-arguments-in-python ? – Chris_Rands Aug 31 '16 at 08:20

2 Answers2

1

You can use argpase module. Refer to the following links :)

https://pymotw.com/2/argparse

Dead simple argparse example wanted: 1 argument, 3 results

Community
  • 1
  • 1
Daewon Lee
  • 620
  • 4
  • 6
1

For me I think python getopt is the way to go.

#!/usr/bin/python

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

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

Usage:

usage: test.py -i <inputfile> -o <outputfile>

It's easier to run when you have a name for the argument.

Ref: http://www.tutorialspoint.com/python/python_command_line_arguments.htm

giaosudau
  • 2,211
  • 6
  • 33
  • 64