Question: Using getopt module to parse and define command line arguments in python
0
gravatar for uxue33
3.0 years ago by
uxue3320
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 = ''

       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

getopt python • 1.8k views
ADD COMMENTlink modified 3.0 years ago by Asaf6.1k • written 3.0 years ago by uxue3320
3

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

ADD REPLYlink written 3.0 years ago by James Ashmore2.6k
4
gravatar for Asaf
3.0 years ago by
Asaf6.1k
Israel
Asaf6.1k 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 3.0 years ago by Asaf6.1k

Thank you very much for your help!

I will try to use this module from now on.

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

Help
Access

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