Question: Using getopt module to parse and define command line arguments in python
gravatar for uxue33
2.6 years ago by
uxue3320 wrote:

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 = ''

          opts, args = getopt.getopt(argv,"l:f:o:",["lista=","fasta=", "output="])
       except getopt.GetoptError:
          print ' -l <lista> -f <fasta>'
       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__":

Thanks in advanced,


getopt python • 1.6k views
ADD COMMENTlink modified 2.6 years ago by Asaf5.2k • written 2.6 years ago by uxue3320

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

ADD REPLYlink written 2.6 years ago by James Ashmore2.6k
gravatar for Asaf
2.6 years ago by
Asaf5.2k wrote:

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 COMMENTlink written 2.6 years ago by Asaf5.2k

Thank you very much for your help!

I will try to use this module from now on.

ADD REPLYlink written 2.6 years ago by uxue3320
Please log in to add an answer.


Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 757 users visited in the last hour