This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Using getopt module to parse and define command line arguments in python

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

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

1 answer

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.

Thank you very much for your help!

I will try to use this module from now on.

Log in to answer this question.