1

I have to read a file from command line arguments using getopt in Python and if I keep -file argument then I couldn't switch the optional arguments order.

Example:

With out File:

python apple.py -debug -help and vise versa (works)

With File:

1) python apple.py **-file abc.txt -debug -help**

(it doesn't work - my requirement)

2) python apple.py **-help -file apple.txt** (works)

3) python apple.py **-debug -file apple.txt** (works)

I want the options to be behave independently - in any order I pass -file then it should read file.

My code implemented like this (apple.py):

 opts , args = getopt.getopt ( sys.argv[1:], "file help debug")

        for opt , arg in opts:
            if opt in ("-f"):
                for line, lines in enumerate(fileinput.input(args)):
                    if line == 2:
                        print(lines)

            elif opt in ("-h"):
                print("it is just a help")

            elif opt in ("-d"):
                print ( "Debug is On" )

python apple.py -file abc.txt -debug -help (doesn't work)

python apple.py -file abc.txt -debug (doesn't work)

I keep get an error which says:

No File or Directory found for -debug

Patrick
  • 5,526
  • 14
  • 64
  • 101
Sudheer
  • 11
  • 3
  • `fileinput.input(args)` --> `fileinput.input(arg)`? – andrew_reece Aug 24 '17 at 03:15
  • i tried fileinput.input(arg) but no it doesn't read file .. fileinput.input(args) --> got me the lines from file when passed python apple.py -file abc.txt – Sudheer Aug 24 '17 at 05:56
  • Try printing out the contents of `opts` and `args` and make sure you're getting the output you expect. – andrew_reece Aug 24 '17 at 05:57
  • yes getopt does work as i wanted i.e. all options are independent but the moment i put file read code into it then .. all options are no more independent .. if i want the file to get red then i should pass like below python apple.py **-help -file apple.txt** – Sudheer Aug 24 '17 at 06:07

0 Answers0