Use sys.exit(msg) i/o print() and sys.exit() (#15465)

Any non-0 exits should be showing an error message
to stderr instead of to stdout.
pull/17130/merge
Adrian Likins 8 years ago committed by Brian Coca
parent 76f9935634
commit 57a911e098

@ -126,6 +126,7 @@ be used to access the machine.
import os import os
import re import re
import argparse import argparse
import sys
from time import time from time import time
import sys import sys
import ConfigParser import ConfigParser
@ -191,9 +192,8 @@ except ImportError:
try: try:
import consul import consul
except ImportError as e: except ImportError as e:
print("""failed=True msg='python-consul required for this module. see sys.exit("""failed=True msg='python-consul required for this module.
http://python-consul.readthedocs.org/en/latest/#installation'""") See http://python-consul.readthedocs.org/en/latest/#installation'""")
sys.exit(1)
from six import iteritems from six import iteritems

@ -147,8 +147,7 @@ except ImportError:
try: try:
from dopy.manager import DoManager from dopy.manager import DoManager
except ImportError as e: except ImportError as e:
print("failed=True msg='`dopy` library required for this script'") sys.exit("failed=True msg='`dopy` library required for this script'")
sys.exit(1)
@ -178,9 +177,9 @@ class DigitalOceanInventory(object):
# Verify credentials were set # Verify credentials were set
if not hasattr(self, 'api_token'): if not hasattr(self, 'api_token'):
print('''Could not find values for DigitalOcean api_token. sys.stderr.write('''Could not find values for DigitalOcean api_token.
They must be specified via either ini file, command line argument (--api-token), They must be specified via either ini file, command line argument (--api-token),
or environment variables (DO_API_TOKEN)''') or environment variables (DO_API_TOKEN)\n''')
sys.exit(-1) sys.exit(-1)
# env command, show DigitalOcean credentials # env command, show DigitalOcean credentials
@ -196,7 +195,7 @@ or environment variables (DO_API_TOKEN)''')
self.load_from_cache() self.load_from_cache()
if len(self.data) == 0: if len(self.data) == 0:
if self.args.force_cache: if self.args.force_cache:
print('''Cache is empty and --force-cache was specified''') sys.stderr.write('''Cache is empty and --force-cache was specified\n''')
sys.exit(-1) sys.exit(-1)
self.manager = DoManager(None, self.api_token, api_version=2) self.manager = DoManager(None, self.api_token, api_version=2)

@ -104,8 +104,7 @@ try:
from libcloud.compute.providers import get_driver from libcloud.compute.providers import get_driver
_ = Provider.GCE _ = Provider.GCE
except: except:
print("GCE inventory script requires libcloud >= 0.13") sys.exit("GCE inventory script requires libcloud >= 0.13")
sys.exit(1)
class GceInventory(object): class GceInventory(object):
@ -205,8 +204,7 @@ class GceInventory(object):
if not secrets_path.endswith('secrets.py'): if not secrets_path.endswith('secrets.py'):
err = "Must specify libcloud secrets file as " err = "Must specify libcloud secrets file as "
err += "/absolute/path/to/secrets.py" err += "/absolute/path/to/secrets.py"
print(err) sys.exit(err)
sys.exit(1)
sys.path.append(os.path.dirname(secrets_path)) sys.path.append(os.path.dirname(secrets_path))
try: try:
import secrets import secrets

@ -34,4 +34,4 @@ if len(sys.argv) == 2 and sys.argv[1] == '--list':
elif len(sys.argv) == 3 and sys.argv[1] == '--host': elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print(json.dumps({'ansible_connection': 'jail'})) print(json.dumps({'ansible_connection': 'jail'}))
else: else:
print("Need an argument, either --list or --host <host>") sys.stderr.write("Need an argument, either --list or --host <host>\n")

@ -34,4 +34,4 @@ if len(sys.argv) == 2 and sys.argv[1] == '--list':
elif len(sys.argv) == 3 and sys.argv[1] == '--host': elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print(json.dumps({'ansible_connection': 'libvirt_lxc'})) print(json.dumps({'ansible_connection': 'libvirt_lxc'}))
else: else:
print("Need an argument, either --list or --host <host>") sys.stderr.write("Need an argument, either --list or --host <host>\n")

@ -185,20 +185,14 @@ class LinodeInventory(object):
for node in Linode.search(status=Linode.STATUS_RUNNING): for node in Linode.search(status=Linode.STATUS_RUNNING):
self.add_node(node) self.add_node(node)
except chube_api.linode_api.ApiError as e: except chube_api.linode_api.ApiError as e:
print("Looks like Linode's API is down:") sys.exit("Looks like Linode's API is down:\n %s" % e)
print("")
print(e)
sys.exit(1)
def get_node(self, linode_id): def get_node(self, linode_id):
"""Gets details about a specific node.""" """Gets details about a specific node."""
try: try:
return Linode.find(api_id=linode_id) return Linode.find(api_id=linode_id)
except chube_api.linode_api.ApiError as e: except chube_api.linode_api.ApiError as e:
print("Looks like Linode's API is down:") sys.exit("Looks like Linode's API is down:\n%" % e)
print("")
print(e)
sys.exit(1)
def populate_datacenter_cache(self): def populate_datacenter_cache(self):
"""Creates self._datacenter_cache, containing all Datacenters indexed by ID.""" """Creates self._datacenter_cache, containing all Datacenters indexed by ID."""

@ -226,5 +226,4 @@ elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
sys.exit(0) sys.exit(0)
else: else:
print("usage: --list ..OR.. --host <hostname>") sys.exit("usage: --list ..OR.. --host <hostname>")
sys.exit(1)

@ -62,8 +62,7 @@ def get_config(env_var, config_var):
if not result: if not result:
result = get_from_rhc_config(config_var) result = get_from_rhc_config(config_var)
if not result: if not result:
print("failed=True msg='missing %s'" % env_var) sys.exit("failed=True msg='missing %s'" % env_var)
sys.exit(1)
return result return result

@ -166,8 +166,7 @@ try:
import pyrax import pyrax
from pyrax.utils import slugify from pyrax.utils import slugify
except ImportError: except ImportError:
print('pyrax is required for this module') sys.exit('pyrax is required for this module')
sys.exit(1)
from time import time from time import time
@ -402,10 +401,9 @@ def setup():
if os.path.isfile(default_creds_file): if os.path.isfile(default_creds_file):
creds_file = default_creds_file creds_file = default_creds_file
elif not keyring_username: elif not keyring_username:
sys.stderr.write('No value in environment variable %s and/or no ' sys.exit('No value in environment variable %s and/or no '
'credentials file at %s\n' 'credentials file at %s'
% ('RAX_CREDS_FILE', default_creds_file)) % ('RAX_CREDS_FILE', default_creds_file))
sys.exit(1)
identity_type = pyrax.get_setting('identity_type') identity_type = pyrax.get_setting('identity_type')
pyrax.set_setting('identity_type', identity_type or 'rackspace') pyrax.set_setting('identity_type', identity_type or 'rackspace')
@ -418,8 +416,7 @@ def setup():
else: else:
pyrax.set_credential_file(creds_file, region=region) pyrax.set_credential_file(creds_file, region=region)
except Exception as e: except Exception as e:
sys.stderr.write("%s: %s\n" % (e, e.message)) sys.exit("%s: %s" % (e, e.message))
sys.exit(1)
regions = [] regions = []
if region: if region:
@ -433,8 +430,7 @@ def setup():
regions = pyrax.regions regions = pyrax.regions
break break
elif region not in pyrax.regions: elif region not in pyrax.regions:
sys.stderr.write('Unsupported region %s' % region) sys.exit('Unsupported region %s' % region)
sys.exit(1)
elif region not in regions: elif region not in regions:
regions.append(region) regions.append(region)

@ -40,4 +40,4 @@ if len(sys.argv) == 2 and sys.argv[1] == '--list':
elif len(sys.argv) == 3 and sys.argv[1] == '--host': elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print(json.dumps({'ansible_connection': 'zone'})) print(json.dumps({'ansible_connection': 'zone'}))
else: else:
print("Need an argument, either --list or --host <host>") sys.stderr.write("Need an argument, either --list or --host <host>\n")

Loading…
Cancel
Save