Python Forum
getopt not working right - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: getopt not working right (/thread-16450.html)



getopt not working right - jdh239 - Feb-28-2019

I am brand new to python. I am trying to utilize getopt to parse some arguments, which kind-of works; however, if I don't pass an argument it doesn't hit the exception, spit out the usage, and exit. I wonder what I have wrong?

def usage():
  print(filename + ": " + "-h|--help -u|--url <url>")

try:
  opts, args = getopt.getopt(sys.argv[1:], 'hu:', ['help', 'url='])
except getopt.GetoptError:
  usage()
  sys.exit(3)

for opt, arg in opts:
  if opt in ('-h', '--help'):
    usage()
    sys.exit(0)
  elif opt in ('-u', '--url'):
    url = arg
  else:
    usage()
    sys.exit(3)
If, for example, I run the script without any arguments, it gets to my requests.get(url) line (not shown) and errors out:
# ./check_pods.py
Traceback (most recent call last):
  File "./check_pods.py", line 31, in <module>
    r = requests.get(url)
  File "/usr/lib/python3.4/site-packages/requests/api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python3.4/site-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 474, in request
    prep = self.prepare_request(req)
  File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 407, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/lib/python3.4/site-packages/requests/models.py", line 302, in prepare
    self.prepare_url(url, params)
  File "/usr/lib/python3.4/site-packages/requests/models.py", line 366, in prepare_url
    raise MissingSchema(error)
requests.exceptions.MissingSchema: Invalid URL '': No schema supplied. Perhaps you meant http://?

This works, but unsure if there is a better way. Feel free to pipe in if you have a better method:

try:
  opts, args = getopt.getopt(sys.argv[1:], 'hu:', ['help', 'url='])
except getopt.GetoptError as err:
  usage()
  sys.exit(3)

if not opts:
  usage()
  sys.exit(3)

for opt, arg in opts:
  if opt in ('-h', '--help'):
    usage()
    sys.exit(0)
  elif opt in ('-u', '--url'):
    url = arg
  else:
    usage()
    sys.exit(3)



RE: getopt not working right - Larz60+ - Feb-28-2019

argparse is easier to use and as far as I know is bug free, as well as well documented.
Please read: https://ttboj.wordpress.com/2010/02/03/getopt-vs-optparse-vs-argparse/