Using getopt module to parse and define command line arguments in python
1
0
Entering edit mode
8.8 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.6k 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.8 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.

#!python
"""See main.__doc__"""
import os
import logging
import glob
import unittest
import sys
import click
import click.testing
module = sys.modules["__main__"].__file__
log = logging.getLogger(module)
def process(filename, output):
"""Do something more useful that printing out the file name"""
print(filename)
@click.command()
@click.argument("files", nargs=-1)
@click.option(
"--output",
help="output directory where to write to",
default=os.getenv("TEMP"),
type=click.Path(),
)
@click.option("--verbose", "-v", help="increases verbosity", count=True)
def main(files, output, verbose):
"""This help line will show in the command line --help output"""
logging.root.setLevel(max(3 - verbose, 0) * 10) # impact all loggers
log.debug("log level: %s", log.getEffectiveLevel())
log.debug("output: %s", output)
# credit https://stackoverflow.com/questions/48604754
all_files = []
for argument in files:
log.debug("processing argument %s ...", argument)
# if our shell does not do filename globbing
expanded = list(glob.glob(argument))
if len(expanded) == 0 and "*" not in argument:
raise (click.BadParameter("{}: file not found".format(argument)))
all_files.extend(expanded)
# Actual processing of the files.
for filename in all_files:
log.info("processing file %s ...", filename)
process(filename, output)
if __name__ == "__main__":
logging.basicConfig(
stream=sys.stderr,
level=logging.DEBUG,
format="%(name)s (%(levelname)s): %(message)s",
)
try:
main()
except KeyboardInterrupt:
log.info("%s interrupted", module)
finally:
logging.shutdown()
class BasicCommandLineTest(unittest.TestCase):
"""Tests can be run with python -m unittest <script>"""
def setUp(self):
self.runner = click.testing.CliRunner()
def test_offers_help_for_invalid_option(self):
"""Shows usage when the option is not valid"""
result = self.runner.invoke(main, ["--invalid"])
self.assertEqual(result.exit_code, 2)
self.assertRegex(result.output, r"Try.*--help")
def test_shows_help(self):
"""Makes sure the help is available."""
result = self.runner.invoke(main, ["--help"])
self.assertEqual(result.exit_code, 0)
self.assertRegex(result.output, r"Usage: ")
def test_one_v_for_info_level_logging(self):
"""-v sets logging to info."""
_ = self.runner.invoke(main, ["-v"])
self.assertEqual(log.getEffectiveLevel(), logging.INFO)
def test_two_v_for_info_level_logging(self):
"""-vv sets logging to debug."""
_ = self.runner.invoke(main, ["-vv"])
self.assertEqual(log.getEffectiveLevel(), logging.DEBUG)
. 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: 1589 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