Merge pull request #12136 from mgedmin/py3k

Python 3: use print() as function under contrib/
This commit is contained in:
Brian Coca 2015-08-28 09:46:24 -04:00
commit c2e84a0a96
28 changed files with 105 additions and 96 deletions

View file

@ -79,7 +79,7 @@ class LibcloudInventory(object):
else:
data_to_print = self.json_format_dict(self.inventory, True)
print data_to_print
print(data_to_print)
def is_cache_valid(self):
@ -282,9 +282,9 @@ class LibcloudInventory(object):
else:
pass
# TODO Product codes if someone finds them useful
#print key
#print type(value)
#print value
#print(key)
#print(type(value))
#print(value)
return self.json_format_dict(instance_vars, True)

View file

@ -70,6 +70,8 @@ based on the data obtained from CloudStack API:
usage: cloudstack.py [--list] [--host HOST] [--project PROJECT]
"""
from __future__ import print_function
import os
import sys
import argparse
@ -83,7 +85,8 @@ except:
try:
from cs import CloudStack, CloudStackException, read_config
except ImportError:
print >> sys.stderr, "Error: CloudStack library must be installed: pip install cs."
print("Error: CloudStack library must be installed: pip install cs.",
file=sys.stderr)
sys.exit(1)
@ -99,7 +102,7 @@ class CloudStackInventory(object):
try:
self.cs = CloudStack(**read_config())
except CloudStackException as e:
print >> sys.stderr, "Error: Could not connect to CloudStack API"
print("Error: Could not connect to CloudStack API", file=sys.stderr)
project_id = ''
if options.project:
@ -107,13 +110,14 @@ class CloudStackInventory(object):
if options.host:
data = self.get_host(options.host)
print json.dumps(data, indent=2)
print(json.dumps(data, indent=2))
elif options.list:
data = self.get_list()
print json.dumps(data, indent=2)
print(json.dumps(data, indent=2))
else:
print >> sys.stderr, "usage: --list | --host <hostname> [--project <project>]"
print("usage: --list | --host <hostname> [--project <project>]",
file=sys.stderr)
sys.exit(1)
@ -123,7 +127,7 @@ class CloudStackInventory(object):
for p in projects['project']:
if p['name'] == project or p['id'] == project:
return p['id']
print >> sys.stderr, "Error: Project %s not found." % project
print("Error: Project %s not found." % project, file=sys.stderr)
sys.exit(1)

View file

@ -113,7 +113,7 @@ class CobblerInventory(object):
self.inventory['_meta']['hostvars'][hostname] = {'cobbler': self.cache[hostname] }
data_to_print += self.json_format_dict(self.inventory, True)
print data_to_print
print(data_to_print)
def _connect(self):
if not self.conn:

View file

@ -164,7 +164,7 @@ class CollinsInventory(object):
else: # default action with no options
data_to_print = self.json_format_dict(self.inventory, self.args.pretty)
print data_to_print
print(data_to_print)
return successful
def find_assets(self, attributes = {}, operation = 'AND'):

View file

@ -137,8 +137,8 @@ except ImportError:
try:
import consul
except ImportError as e:
print """failed=True msg='python-consul required for this module. see
http://python-consul.readthedocs.org/en/latest/#installation'"""
print("""failed=True msg='python-consul required for this module. see
http://python-consul.readthedocs.org/en/latest/#installation'""")
sys.exit(1)
@ -171,7 +171,7 @@ class ConsulInventory(object):
self.load_all_data_consul()
self.combine_all_results()
print json.dumps(self.inventory, sort_keys=True, indent=2)
print(json.dumps(self.inventory, sort_keys=True, indent=2))
def load_all_data_consul(self):
''' cycle through each of the datacenters in the consul catalog and process

View file

@ -146,7 +146,7 @@ except ImportError:
try:
from dopy.manager import DoError, DoManager
except ImportError as e:
print "failed=True msg='`dopy` library required for this script'"
print("failed=True msg='`dopy` library required for this script'")
sys.exit(1)
@ -175,14 +175,14 @@ class DigitalOceanInventory(object):
# Verify credentials were set
if not hasattr(self, 'api_token'):
print '''Could not find values for DigitalOcean api_token.
print('''Could not find values for DigitalOcean 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)''')
sys.exit(-1)
# env command, show DigitalOcean credentials
if self.args.env:
print "DO_API_TOKEN=%s" % self.api_token
print("DO_API_TOKEN=%s" % self.api_token)
sys.exit(0)
# Manage cache
@ -193,7 +193,7 @@ or environment variables (DO_API_TOKEN)'''
self.load_from_cache()
if len(self.data) == 0:
if self.args.force_cache:
print '''Cache is empty and --force-cache was specified'''
print('''Cache is empty and --force-cache was specified''')
sys.exit(-1)
self.manager = DoManager(None, self.api_token, api_version=2)
@ -231,9 +231,9 @@ or environment variables (DO_API_TOKEN)'''
self.write_to_cache()
if self.args.pretty:
print json.dumps(json_data, sort_keys=True, indent=2)
print(json.dumps(json_data, sort_keys=True, indent=2))
else:
print json.dumps(json_data)
print(json.dumps(json_data))
# That's all she wrote...

View file

@ -334,7 +334,7 @@ def list_groups():
groups['docker_hosts'] = [host.get('base_url') for host in hosts]
groups['_meta'] = dict()
groups['_meta']['hostvars'] = hostvars
print json.dumps(groups, sort_keys=True, indent=4)
print(json.dumps(groups, sort_keys=True, indent=4))
sys.exit(0)

View file

@ -81,7 +81,7 @@ if options.list:
for data in ssh_config:
hosts['coreos'].append(data['Host'])
print json.dumps(hosts)
print(json.dumps(hosts))
sys.exit(1)
# Get out the host details
@ -96,7 +96,7 @@ elif options.host:
result = details[0]
result
print json.dumps(result)
print(json.dumps(result))
sys.exit(1)

View file

@ -41,7 +41,7 @@ def list_groups(api):
inventory['_meta'] = {'hostvars': hostvars}
inv_string = json.dumps(inventory, indent=1, sort_keys=True)
print inv_string
print(inv_string)
return None
@ -69,7 +69,7 @@ def print_host(host):
This function expects one string, this hostname to lookup variables for.
'''
print json.dumps({})
print(json.dumps({}))
return None

View file

@ -112,9 +112,9 @@ class GceInventory(object):
# Just display data for specific host
if self.args.host:
print self.json_format_dict(self.node_to_dict(
print(self.json_format_dict(self.node_to_dict(
self.get_instance(self.args.host)),
pretty=self.args.pretty)
pretty=self.args.pretty))
sys.exit(0)
# Otherwise, assume user wants all instances grouped

View file

@ -30,8 +30,8 @@ result['all']['vars'] = {}
result['all']['vars']['ansible_connection'] = 'jail'
if len(sys.argv) == 2 and sys.argv[1] == '--list':
print json.dumps(result)
print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print json.dumps({'ansible_connection': 'jail'})
print(json.dumps({'ansible_connection': 'jail'}))
else:
print "Need an argument, either --list or --host <host>"
print("Need an argument, either --list or --host <host>")

View file

@ -30,8 +30,8 @@ result['all']['vars'] = {}
result['all']['vars']['ansible_connection'] = 'lxc'
if len(sys.argv) == 2 and sys.argv[1] == '--list':
print json.dumps(result)
print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print json.dumps({'ansible_connection': 'lxc'})
print(json.dumps({'ansible_connection': 'lxc'}))
else:
print "Need an argument, either --list or --host <host>"
print("Need an argument, either --list or --host <host>")

View file

@ -139,7 +139,7 @@ class LinodeInventory(object):
else:
data_to_print = self.json_format_dict(self.inventory, True)
print data_to_print
print(data_to_print)
def is_cache_valid(self):
"""Determines if the cache file has expired, or if it is still valid."""
@ -185,9 +185,9 @@ class LinodeInventory(object):
for node in Linode.search(status=Linode.STATUS_RUNNING):
self.add_node(node)
except chube_api.linode_api.ApiError as e:
print "Looks like Linode's API is down:"
print
print e
print("Looks like Linode's API is down:")
print("")
print(e)
sys.exit(1)
def get_node(self, linode_id):
@ -195,9 +195,9 @@ class LinodeInventory(object):
try:
return Linode.find(api_id=linode_id)
except chube_api.linode_api.ApiError as e:
print "Looks like Linode's API is down:"
print
print e
print("Looks like Linode's API is down:")
print("")
print(e)
sys.exit(1)
def populate_datacenter_cache(self):

View file

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

View file

@ -61,7 +61,7 @@ def get_config(env_var, config_var):
if not result:
result = get_from_rhc_config(config_var)
if not result:
print "failed=True msg='missing %s'" % env_var
print("failed=True msg='missing %s'" % env_var)
sys.exit(1)
return result
@ -109,8 +109,8 @@ for app in response:
result[app_name]['vars']['ansible_ssh_user'] = user
if len(sys.argv) == 2 and sys.argv[1] == '--list':
print json.dumps(result)
print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print json.dumps({})
print(json.dumps({}))
else:
print "Need an argument, either --list or --host <host>"
print("Need an argument, either --list or --host <host>")

View file

@ -70,8 +70,8 @@ def get_guests():
if len(sys.argv) == 2 and sys.argv[1] == '--list':
inv_json = get_guests()
print json.dumps(inv_json, sort_keys=True)
print(json.dumps(inv_json, sort_keys=True))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print json.dumps({});
print(json.dumps({}))
else:
print "Need an argument, either --list or --host <host>"
print("Need an argument, either --list or --host <host>")

View file

@ -95,10 +95,10 @@ class OVirtInventory(object):
# Just display data for specific host
if self.args.host:
print self.json_format_dict(
print(self.json_format_dict(
self.node_to_dict(self.get_instance(self.args.host)),
pretty=self.args.pretty
)
))
sys.exit(0)
# Otherwise, assume user wants all instances grouped

View file

@ -172,7 +172,7 @@ def main():
if options.pretty:
indent = 2
print json.dumps(data, indent=indent)
print(json.dumps(data, indent=indent))
if __name__ == '__main__':
main()

View file

@ -53,10 +53,10 @@ class SoftLayerInventory(object):
if self.args.list:
self.get_all_servers()
print self.json_format_dict(self.inventory, True)
print(self.json_format_dict(self.inventory, True))
elif self.args.host:
self.get_virtual_servers()
print self.json_format_dict(self.inventory["_meta"]["hostvars"][self.args.host], True)
print(self.json_format_dict(self.inventory["_meta"]["hostvars"][self.args.host], True))
def to_safe(self, word):
'''Converts 'bad' characters in a string to underscores so they can be used as Ansible groups'''

View file

@ -40,6 +40,8 @@ Tested with Ansible 1.9.2 and spacewalk 2.3
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import print_function
import sys
import os
import time
@ -60,7 +62,7 @@ INI_FILE = os.path.join(base_dir, "spacewalk.ini")
# Sanity check
if not os.path.exists(SW_REPORT):
print >> sys.stderr, 'Error: %s is required for operation.' % (SW_REPORT)
print('Error: %s is required for operation.' % (SW_REPORT), file=sys.stderr)
sys.exit(1)
# Pre-startup work
@ -133,8 +135,8 @@ try:
org_groups[group['spacewalk_group_id']] = group['spacewalk_org_id']
except (OSError) as e:
print >> sys.stderr, 'Problem executing the command "%s system-groups": %s' % \
(SW_REPORT, str(e))
print('Problem executing the command "%s system-groups": %s' %
(SW_REPORT, str(e)), file=sys.stderr)
sys.exit(2)
@ -149,8 +151,8 @@ if options.list:
host_vars[ item['spacewalk_profile_name'] ] = dict( ( key, ( value.split(';') if ';' in value else value) ) for key, value in item.items() )
except (OSError) as e:
print >> sys.stderr, 'Problem executing the command "%s inventory": %s' % \
(SW_REPORT, str(e))
print('Problem executing the command "%s inventory": %s' %
(SW_REPORT, str(e)), file=sys.stderr)
sys.exit(2)
groups = {}
@ -186,18 +188,18 @@ if options.list:
meta[ "hostvars" ][ system['spacewalk_server_name'] ] = host_vars[ system['spacewalk_server_name'] ]
except (OSError) as e:
print >> sys.stderr, 'Problem executing the command "%s system-groups-systems": %s' % \
(SW_REPORT, str(e))
print('Problem executing the command "%s system-groups-systems": %s' %
(SW_REPORT, str(e)), file=sys.stderr)
sys.exit(2)
if options.human:
for group, systems in groups.iteritems():
print '[%s]\n%s\n' % (group, '\n'.join(systems))
print('[%s]\n%s\n' % (group, '\n'.join(systems)))
else:
final = dict( [ (k, list(s)) for k, s in groups.iteritems() ] )
final["_meta"] = meta
print json.dumps( final )
#print json.dumps(groups)
print(json.dumps( final ))
#print(json.dumps(groups))
sys.exit(0)
@ -213,16 +215,16 @@ elif options.host:
break
except (OSError) as e:
print >> sys.stderr, 'Problem executing the command "%s inventory": %s' % \
(SW_REPORT, str(e))
print('Problem executing the command "%s inventory": %s' %
(SW_REPORT, str(e)), file=sys.stderr)
sys.exit(2)
if options.human:
print 'Host: %s' % options.host
print('Host: %s' % options.host)
for k, v in host_details.iteritems():
print ' %s: %s' % (k, '\n '.join(v.split(';')))
print(' %s: %s' % (k, '\n '.join(v.split(';'))))
else:
print json.dumps( dict( ( key, ( value.split(';') if ';' in value else value) ) for key, value in host_details.items() ) )
print( json.dumps( dict( ( key, ( value.split(';') if ';' in value else value) ) for key, value in host_details.items() ) ) )
sys.exit(0)
else:

View file

@ -99,12 +99,12 @@ def print_list():
if tmp_dict:
meta['hostvars'][alias] = tmp_dict
print json.dumps({_key: list(set(meta['hostvars'].keys())), '_meta': meta})
print(json.dumps({_key: list(set(meta['hostvars'].keys())), '_meta': meta}))
def print_host(host):
cfg = get_config()
print json.dumps(cfg[host])
print(json.dumps(cfg[host]))
def get_args(args_list):

View file

@ -113,13 +113,13 @@ if options.list:
for host in ssh_config:
meta['hostvars'][host] = ssh_config[host]
print json.dumps({_group: list(ssh_config.keys()), '_meta': meta})
print(json.dumps({_group: list(ssh_config.keys()), '_meta': meta}))
sys.exit(0)
# Get out the host details
# ------------------------------
elif options.host:
print json.dumps(get_a_ssh_config(options.host))
print(json.dumps(get_a_ssh_config(options.host)))
sys.exit(0)
# Print out help

View file

@ -111,4 +111,4 @@ if __name__ == '__main__':
inventory = get_hosts()
import pprint
print pprint.pprint(inventory)
pprint.pprint(inventory)

View file

@ -28,6 +28,8 @@ take precedence over options present in the INI file. An INI file is not
required if these options are specified using environment variables.
'''
from __future__ import print_function
import collections
import json
import logging
@ -208,7 +210,7 @@ class VMwareInventory(object):
try:
host_info['ipAddress'] = host.config.network.vnic[0].spec.ip.ipAddress
except Exception as e:
print >> sys.stderr, e
print(e, file=sys.stderr)
host_info = self._flatten_dict(host_info, prefix)
if ('%s_ipAddress' % prefix) in host_info:
host_info['ansible_ssh_host'] = host_info['%s_ipAddress' % prefix]

View file

@ -51,7 +51,7 @@ try:
from azure import WindowsAzureError
from azure.servicemanagement import ServiceManagementService
except ImportError as e:
print "failed=True msg='`azure` library required for this script'"
print("failed=True msg='`azure` library required for this script'")
sys.exit(1)
@ -109,7 +109,7 @@ class AzureInventory(object):
# JSONify the data.
data_to_print = self.json_format_dict(data, pretty=True)
print data_to_print
print(data_to_print)
def get_host(self, hostname, jsonify=True):
"""Return information about the given hostname, based on what
@ -195,9 +195,9 @@ class AzureInventory(object):
for cloud_service in self.sms.list_hosted_services():
self.add_deployments(cloud_service)
except WindowsAzureError as e:
print "Looks like Azure's API is down:"
print
print e
print("Looks like Azure's API is down:")
print("")
print(e)
sys.exit(1)
def add_deployments(self, cloud_service):
@ -208,9 +208,9 @@ class AzureInventory(object):
for deployment in self.sms.get_hosted_service_properties(cloud_service.service_name,embed_detail=True).deployments.deployments:
self.add_deployment(cloud_service, deployment)
except WindowsAzureError as e:
print "Looks like Azure's API is down:"
print
print e
print("Looks like Azure's API is down:")
print("")
print(e)
sys.exit(1)
def add_deployment(self, cloud_service, deployment):

View file

@ -30,6 +30,8 @@ Configuration is read from `zabbix.ini`.
Tested with Zabbix Server 2.0.6.
"""
from __future__ import print_function
import os, sys
import argparse
import ConfigParser
@ -37,7 +39,8 @@ import ConfigParser
try:
from zabbix_api import ZabbixAPI
except:
print >> sys.stderr, "Error: Zabbix API library must be installed: pip install zabbix-api."
print("Error: Zabbix API library must be installed: pip install zabbix-api.",
file=sys.stderr)
sys.exit(1)
try:
@ -110,23 +113,23 @@ class ZabbixInventory(object):
api = ZabbixAPI(server=self.zabbix_server)
api.login(user=self.zabbix_username, password=self.zabbix_password)
except BaseException as e:
print >> sys.stderr, "Error: Could not login to Zabbix server. Check your zabbix.ini."
print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr)
sys.exit(1)
if self.options.host:
data = self.get_host(api, self.options.host)
print json.dumps(data, indent=2)
print(json.dumps(data, indent=2))
elif self.options.list:
data = self.get_list(api)
print json.dumps(data, indent=2)
print(json.dumps(data, indent=2))
else:
print >> sys.stderr, "usage: --list ..OR.. --host <hostname>"
print("usage: --list ..OR.. --host <hostname>", file=sys.stderr)
sys.exit(1)
else:
print >> sys.stderr, "Error: Configuration of server and credentials are required. See zabbix.ini."
print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr)
sys.exit(1)
ZabbixInventory()

View file

@ -36,8 +36,8 @@ result['all']['vars'] = {}
result['all']['vars']['ansible_connection'] = 'zone'
if len(sys.argv) == 2 and sys.argv[1] == '--list':
print json.dumps(result)
print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
print json.dumps({'ansible_connection': 'zone'})
print(json.dumps({'ansible_connection': 'zone'}))
else:
print "Need an argument, either --list or --host <host>"
print("Need an argument, either --list or --host <host>")

View file

@ -26,9 +26,7 @@ whitelist_externals = make
[testenv:py34]
commands =
python --version
# scripts in contrib still need to be ported to python3-compatible syntax
#python -m compileall -fq -x 'lib/ansible/module_utils|lib/ansible/modules' lib test contrib
python -m compileall -fq -x 'lib/ansible/module_utils|lib/ansible/modules' lib test
python -m compileall -fq -x 'lib/ansible/module_utils|lib/ansible/modules' lib test contrib
# Unittests need lots of work to make code python3 compatible
#make tests
deps = -r{toxinidir}/test-requirements.txt