Using getopt module to parse and define command line arguments in python
1
0
Entering edit mode
8.4 years ago
uxue33 ▴ 20

I'm beginning to learn how to use python to develop some tasks in the lab.

I have tried to use the getopt.getopt method to define the command line arguments but when I run the program gives an error, telling that output_file is not defined.

Here is my code:

  def main(argv):

       lista_file = ''
       fasta_file = ''
       output_file = ''

       try:
          opts, args = getopt.getopt(argv,"l:f:o:",["lista=","fasta=", "output="])
       except getopt.GetoptError:
          print 'test.py -l <lista> -f <fasta>'
          sys.exit(2)
       for opt, arg in opts:
          if opt in ("-l", "--lista"):
             lista_file = arg
          elif opt in ("-f", "--fasta"):
             fasta_file = arg
          elif opt in ("-o", "--output"):
             output_file = arg

          print 'Lista is:  "', lista_file
          print 'Fasta is "', fasta_file
          print 'Output is "', output_file

       return lista_file
       return fasta_file
       return output_file

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

Thanks in advanced,

Uxue

python getopt • 4.4k views
ADD COMMENT
3
Entering edit mode

The getopt module is deprecated, I'd suggest learning the new argparse module.

ADD REPLY
4
Entering edit mode
8.4 years ago
Asaf 10k

This is not how you should use it. You better use argparse instead of getopt. I use a skeleton script, many of whom can be found online, e.g. . Whenever you start a new script copy this skeleton to a new file and start filling in the parameters and code. A good habit is not to have any parameter hard-coded in the code, if you're writing a line and need a parameter just add it to the parameters function and set a default value.

ADD COMMENT
0
Entering edit mode

Thank you very much for your help!

I will try to use this module from now on.

ADD REPLY

Login before adding your answer.

Traffic: 1553 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6