From: Thierry Parmentelat Date: Thu, 31 Mar 2016 06:55:05 +0000 (+0200) Subject: 2to3 -f print X-Git-Tag: sfa-3.1-21~33 X-Git-Url: http://git.onelab.eu/?p=sfa.git;a=commitdiff_plain;h=fad16c7d54b658b37a9b42fbee47b0d4f51cb8ec 2to3 -f print from __future__ import print_function --- diff --git a/sfa/client/candidates.py b/sfa/client/candidates.py index f3a99ae3..830e24d8 100644 --- a/sfa/client/candidates.py +++ b/sfa/client/candidates.py @@ -1,3 +1,5 @@ +from __future__ import print_function + ### utility to match command-line args to names class Candidates: def __init__ (self, names): @@ -43,8 +45,8 @@ def test_candidates (): names=names.split() for (input,expected) in tuples: got=Candidates(names).only_match(input) - if got==expected: print '.', - else: print 'X FAIL','names[',names,'] input',input,'expected',expected,'got',got + if got==expected: print('.', end=' ') + else: print('X FAIL','names[',names,'] input',input,'expected',expected,'got',got) if __name__ == '__main__': test_candidates() diff --git a/sfa/client/common.py b/sfa/client/common.py index 52ae3eef..16a06940 100644 --- a/sfa/client/common.py +++ b/sfa/client/common.py @@ -1,5 +1,7 @@ # a few utilities common to sfi and sfaadmin +from __future__ import print_function + def optparse_listvalue_callback(option, opt, value, parser): former=getattr(parser.values,option.dest) if not former: former=[] @@ -41,37 +43,37 @@ def terminal_render_plural (how_many, name,names=None): else: return "%d %s"%(how_many,names) def terminal_render_default (record,options): - print "%s (%s)" % (record['hrn'], record['type']) + print("%s (%s)" % (record['hrn'], record['type'])) def terminal_render_user (record, options): - print "%s (User)"%record['hrn'], + print("%s (User)"%record['hrn'], end=' ') if options.verbose and record.get('email', None): - print "email='{}'".format(record['email']), + print("email='{}'".format(record['email']), end=' ') if record.get('reg-pi-authorities', None): - print " [PI at %s]"%(" and ".join(record['reg-pi-authorities'])), + print(" [PI at %s]"%(" and ".join(record['reg-pi-authorities'])), end=' ') if record.get('reg-slices', None): - print " [IN slices %s]"%(" and ".join(record['reg-slices'])), + print(" [IN slices %s]"%(" and ".join(record['reg-slices'])), end=' ') user_keys=record.get('reg-keys',[]) if not options.verbose: - print " [has %s]"%(terminal_render_plural(len(user_keys),"key")) + print(" [has %s]"%(terminal_render_plural(len(user_keys),"key"))) else: - print "" - for key in user_keys: print 8*' ',key.strip("\n") + print("") + for key in user_keys: print(8*' ',key.strip("\n")) def terminal_render_slice (record, options): - print "%s (Slice)"%record['hrn'], + print("%s (Slice)"%record['hrn'], end=' ') if record.get('reg-researchers', None): - print " [USERS %s]"%(" and ".join(record['reg-researchers'])), + print(" [USERS %s]"%(" and ".join(record['reg-researchers'])), end=' ') # print record.keys() - print "" + print("") def terminal_render_authority (record, options): - print "%s (Authority)"%record['hrn'], + print("%s (Authority)"%record['hrn'], end=' ') if options.verbose and record.get('name'): - print "name='{}'".format(record['name']) + print("name='{}'".format(record['name'])) if record.get('reg-pis', None): - print " [PIS %s]"%(" and ".join(record['reg-pis'])), - print "" + print(" [PIS %s]"%(" and ".join(record['reg-pis'])), end=' ') + print("") def terminal_render_node (record, options): - print "%s (Node)"%record['hrn'] + print("%s (Node)"%record['hrn']) ### used in sfi list diff --git a/sfa/client/multiclient.py b/sfa/client/multiclient.py index 75573ed5..28b5b15a 100644 --- a/sfa/client/multiclient.py +++ b/sfa/client/multiclient.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import threading import traceback import time @@ -95,14 +97,14 @@ if __name__ == '__main__': def f(name, n, sleep=1): nums = [] for i in range(n, n+5): - print "%s: %s" % (name, i) + print("%s: %s" % (name, i)) nums.append(i) time.sleep(sleep) return nums def e(name, n, sleep=1): nums = [] for i in range(n, n+3) + ['n', 'b']: - print "%s: 1 + %s:" % (name, i) + print("%s: 1 + %s:" % (name, i)) nums.append(i + 1) time.sleep(sleep) return nums diff --git a/sfa/client/sfaadmin.py b/sfa/client/sfaadmin.py index a21cb5f6..49757b32 100755 --- a/sfa/client/sfaadmin.py +++ b/sfa/client/sfaadmin.py @@ -1,4 +1,6 @@ #!/usr/bin/python +from __future__ import print_function + import os import sys import copy @@ -130,15 +132,15 @@ class RegistryCommands(Commands): hrn = Xrn(xrn).get_hrn() db_query = db_query.filter_by(hrn=hrn) elif all and xrn: - print "Use either -a or -x , not both !!!" + print("Use either -a or -x , not both !!!") sys.exit(1) elif not all and not xrn: - print "Use either -a or -x , one of them is mandatory !!!" + print("Use either -a or -x , one of them is mandatory !!!") sys.exit(1) records = db_query.all() if not records: - print "No Record found" + print("No Record found") sys.exit(1) OK = [] @@ -171,15 +173,15 @@ class RegistryCommands(Commands): NOK.append(record.hrn) if not verbose: - print "Users NOT having a PubKey: %s\n\ + print("Users NOT having a PubKey: %s\n\ Users having a non RSA PubKey: %s\n\ Users having a GID/PubKey correpondence OK: %s\n\ -Users having a GID/PubKey correpondence Not OK: %s\n"%(len(NOKEY), len(ERROR), len(OK), len(NOK)) +Users having a GID/PubKey correpondence Not OK: %s\n"%(len(NOKEY), len(ERROR), len(OK), len(NOK))) else: - print "Users NOT having a PubKey: %s and are: \n%s\n\n\ + print("Users NOT having a PubKey: %s and are: \n%s\n\n\ Users having a non RSA PubKey: %s and are: \n%s\n\n\ Users having a GID/PubKey correpondence OK: %s and are: \n%s\n\n\ -Users having a GID/PubKey correpondence NOT OK: %s and are: \n%s\n\n"%(len(NOKEY),NOKEY, len(ERROR), ERROR, len(OK), OK, len(NOK), NOK) +Users having a GID/PubKey correpondence NOT OK: %s and are: \n%s\n\n"%(len(NOKEY),NOKEY, len(ERROR), ERROR, len(OK), OK, len(NOK), NOK)) @@ -252,7 +254,7 @@ Users having a GID/PubKey correpondence NOT OK: %s and are: \n%s\n\n"%(len(NOKEY def credential(self, xrn, type=None): """Invoke GetCredential""" cred = self.api.manager.GetCredential(self.api, xrn, type, self.api.hrn) - print cred + print(cred) def import_registry(self): @@ -337,7 +339,7 @@ class CertCommands(Commands): auth_info = hierarchy.get_auth_info(hrn) gid = auth_info.gid_object except: - print "Record: %s not found" % hrn + print("Record: %s not found" % hrn) sys.exit(1) # save to file if not outfile: @@ -349,7 +351,7 @@ class CertCommands(Commands): """Print contents of a GID file""" gid_path = os.path.abspath(gidfile) if not gid_path or not os.path.isfile(gid_path): - print "No such gid file: %s" % gidfile + print("No such gid file: %s" % gidfile) sys.exit(1) gid = GID(filename=gid_path) gid.dump(dump_parents=True) @@ -377,9 +379,9 @@ class AggregateCommands(Commands): def resources(self, rspec_version='GENI'): """Display the available resources at an aggregate""" options = {'geni_rspec_version': rspec_version} - print options + print(options) resources = self.api.manager.ListResources(self.api, [], options) - print resources + print(resources) @add_options('-x', '--xrn', dest='xrn', metavar='', help='slice hrn/urn (mandatory)') @@ -391,7 +393,7 @@ class AggregateCommands(Commands): rspec_string = open(rspec).read() options={} manifest = self.api.manager.Allocate(self.api, slice_urn, [], rspec_string, options) - print manifest + print(manifest) @add_options('-x', '--xrn', dest='xrn', metavar='', help='slice hrn/urn (mandatory)') @@ -401,7 +403,7 @@ class AggregateCommands(Commands): slice_urn=xrn.get_urn() options={} manifest = self.api.manager.provision(self.api, [slice_urn], [], options) - print manifest + print(manifest) @@ -433,14 +435,14 @@ class SfaAdmin: return (full_name,SfaAdmin.CATEGORIES[full_name]) def summary_usage (self, category=None): - print "Usage:", self.script_name + " category command []" + print("Usage:", self.script_name + " category command []") if category and category in SfaAdmin.CATEGORIES: categories=[category] else: categories=SfaAdmin.CATEGORIES for c in categories: cls=SfaAdmin.CATEGORIES[c] - print "==================== category=%s"%c + print("==================== category=%s"%c) names=cls.__dict__.keys() names.sort() for name in names: @@ -448,15 +450,15 @@ class SfaAdmin: if name.startswith('_'): continue margin=15 format="%%-%ds"%margin - print "%-15s"%name, + print("%-15s"%name, end=' ') doc=getattr(method,'__doc__',None) if not doc: - print "" + print("") continue lines=[line.strip() for line in doc.split("\n")] line1=lines.pop(0) - print line1 - for extra_line in lines: print margin*" ",extra_line + print(line1) + for extra_line in lines: print(margin*" ",extra_line) sys.exit(2) def main(self): @@ -509,14 +511,14 @@ class SfaAdmin: command(*cmd_args, **cmd_kwds) sys.exit(0) except TypeError: - print "Possible wrong number of arguments supplied" + print("Possible wrong number of arguments supplied") #import traceback #traceback.print_exc() - print command.__doc__ + print(command.__doc__) parser.print_help() sys.exit(1) #raise except Exception: - print "Command failed, please check log for more info" + print("Command failed, please check log for more info") raise sys.exit(1) diff --git a/sfa/client/sfaclientlib.py b/sfa/client/sfaclientlib.py index bc4a1d14..ccdf36ac 100644 --- a/sfa/client/sfaclientlib.py +++ b/sfa/client/sfaclientlib.py @@ -1,7 +1,9 @@ # Thierry Parmentelat -- INRIA -# -# a minimal library for writing "lightweight" SFA clients -# +""" +a minimal library for writing "lightweight" SFA clients +""" + +from __future__ import print_function # xxx todo # this library should probably check for the expiration date of the various @@ -217,9 +219,9 @@ class SfaClientBootstrap: openssl_command += [ "-in", self.my_gid_filename()] openssl_command += [ "-out", filename ] if subprocess.call(openssl_command) ==0: - print "Successfully created %s"%filename + print("Successfully created %s"%filename) else: - print "Failed to create %s"%filename + print("Failed to create %s"%filename) # Returns True if credential file is valid. Otherwise return false. def validate_credential(self, filename): diff --git a/sfa/client/sfascan.py b/sfa/client/sfascan.py index f7f5ddab..d3ae2fdb 100644 --- a/sfa/client/sfascan.py +++ b/sfa/client/sfascan.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import sys, os.path import pickle import time @@ -8,7 +10,7 @@ from urlparse import urlparse try: import pygraphviz except: - print 'Warning, could not import pygraphviz, test mode only' + print('Warning, could not import pygraphviz, test mode only') from optparse import OptionParser @@ -73,7 +75,7 @@ class VersionCache: def show (self): entries=len(self.url2version) - print "version cache from file %s has %d entries"%(self.filename,entries) + print("version cache from file %s has %d entries"%(self.filename,entries)) key_values=self.url2version.items() def old_first (kv1,kv2): return int(kv1[1][0]-kv2[1][0]) key_values.sort(old_first) @@ -82,9 +84,9 @@ class VersionCache: (timestamp,version) = tuple how_old = time.time()-timestamp if how_old<=self.expires: - print url,"-- %d seconds ago"%how_old + print(url,"-- %d seconds ago"%how_old) else: - print "OUTDATED",url,"(%d seconds ago, expires=%d)"%(how_old,self.expires) + print("OUTDATED",url,"(%d seconds ago, expires=%d)"%(how_old,self.expires)) # turns out we might have trailing slashes or not def normalize (self, url): @@ -366,5 +368,5 @@ class SfaScan: # test mode when pygraphviz is not available except: entry=entries[0] - print "GetVersion at %s returned %s"%(entry.url(),entry.get_version()) + print("GetVersion at %s returned %s"%(entry.url(),entry.get_version())) diff --git a/sfa/dummy/dummy_testbed_api_client.py b/sfa/dummy/dummy_testbed_api_client.py index 38ba0d3b..4b3989ef 100644 --- a/sfa/dummy/dummy_testbed_api_client.py +++ b/sfa/dummy/dummy_testbed_api_client.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import xmlrpclib from datetime import datetime import time @@ -11,6 +13,6 @@ my_user_id = dummy_api.AddUser({'email': 'john.doe@test.net', 'user_name': 'john dummy_api.AddUserToSlice({'slice_id': 2, 'user_id': my_user_id}) # Display the list of users -print dummy_api.GetUsers() +print(dummy_api.GetUsers()) # Display the list of slices -print dummy_api.GetSlices() +print(dummy_api.GetSlices()) diff --git a/sfa/examples/miniclient.py b/sfa/examples/miniclient.py index 1c625e07..535b4465 100755 --- a/sfa/examples/miniclient.py +++ b/sfa/examples/miniclient.py @@ -3,6 +3,8 @@ # this is designed to use a totally empty new directory # so we demonstrate how to bootstrap the whole thing +from __future__ import print_function + # init logging on console import logging console = logging.StreamHandler() @@ -17,7 +19,7 @@ def unique_call_id(): return uuid.uuid4().urn import sys args=sys.argv[1:] if len(args)!=1: - print "Usage: %s directory"%sys.argv[0] + print("Usage: %s directory"%sys.argv[0]) sys.exit(1) dir=args[0] logger.debug('sfaclientsample: Using directory %s'%dir) @@ -62,8 +64,8 @@ def get_version (url): bootstrap.self_signed_cert() server_proxy = bootstrap.server_proxy_simple(url) server_version = server_proxy.GetVersion() - print "miniclient: GetVersion at %s returned:"%(url) - for (k,v) in server_version.iteritems(): print "miniclient: \tversion[%s]=%s"%(k,truncate(v)) + print("miniclient: GetVersion at %s returned:"%(url)) + for (k,v) in server_version.iteritems(): print("miniclient: \tversion[%s]=%s"%(k,truncate(v))) # version_dict = {'type': 'SFA', 'version': '1', } @@ -79,7 +81,7 @@ def list_resources (): options [ 'geni_rspec_version' ] = version_dict options [ 'call_id' ] = unique_call_id() list_resources = bootstrap.server_proxy (aggregate_url).ListResources(credentials,options) - print "miniclient: ListResources at %s returned : %s"%(aggregate_url,truncate(list_resources)) + print("miniclient: ListResources at %s returned : %s"%(aggregate_url,truncate(list_resources))) def list_slice_resources (): bootstrap.bootstrap_my_gid() @@ -90,7 +92,7 @@ def list_slice_resources (): options [ 'geni_slice_urn' ] = slice_urn options [ 'call_id' ] = unique_call_id() list_resources = bootstrap.server_proxy (aggregate_url).ListResources(credentials,options) - print "miniclient: ListResources at %s for slice %s returned : %s"%(aggregate_url,slice_urn,truncate(list_resources)) + print("miniclient: ListResources at %s for slice %s returned : %s"%(aggregate_url,slice_urn,truncate(list_resources))) diff --git a/sfa/managers/eucalyptus/euca_rspec_validator.py b/sfa/managers/eucalyptus/euca_rspec_validator.py index 7e25063d..7ebaae5b 100755 --- a/sfa/managers/eucalyptus/euca_rspec_validator.py +++ b/sfa/managers/eucalyptus/euca_rspec_validator.py @@ -1,6 +1,7 @@ #!/usr/bin/env python -from __future__ import with_statement +from __future__ import print_function + import sys import os from lxml import etree as ET @@ -19,9 +20,9 @@ def main(): if not rspecValidator(rspecXML): error = rspecValidator.error_log.last_error message = '%s (line %s)' % (error.message, error.line) - print message + print(message) else: - print 'It is valid' + print('It is valid') if __name__ == "__main__": main() diff --git a/sfa/managers/registry_manager.py b/sfa/managers/registry_manager.py index 1eafc10f..a88c9de0 100644 --- a/sfa/managers/registry_manager.py +++ b/sfa/managers/registry_manager.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import types # for get_key_from_incoming_ip import tempfile @@ -503,7 +505,7 @@ class RegistryManager: # record.__dict__ as received by the driver seems to be off # anyway the driver should receive an object # (and then extract __dict__ itself if needed) - print "DO NOT REMOVE ME before driver.update, record={}".format(record) + print("DO NOT REMOVE ME before driver.update, record={}".format(record)) # as of June 2015: I suspect we could remove that print line above and replace it with # augment_with_sfa_builtins(record) # instead, that checks for these fields, like it is done above in List() diff --git a/sfa/nitos/nitosxrn.py b/sfa/nitos/nitosxrn.py index 47d8aadf..9722ffed 100644 --- a/sfa/nitos/nitosxrn.py +++ b/sfa/nitos/nitosxrn.py @@ -1,3 +1,5 @@ +from __future__ import print_function + # specialized Xrn class for NITOS import re from sfa.util.xrn import Xrn @@ -110,4 +112,4 @@ if __name__ == '__main__': #slice_name = NitosXrn(xrn="omf.nitos.aminesl",type='slice').nitos_slicename() slicename = "giorgos_n" hrn = slicename_to_hrn("pla", "nitos", slicename) - print hrn + print(hrn) diff --git a/sfa/planetlab/plxrn.py b/sfa/planetlab/plxrn.py index b6010c94..70ff5e02 100644 --- a/sfa/planetlab/plxrn.py +++ b/sfa/planetlab/plxrn.py @@ -1,3 +1,5 @@ +from __future__ import print_function + # specialized Xrn class for PlanetLab import re from sfa.util.xrn import Xrn, get_authority @@ -114,4 +116,4 @@ tests = [ if __name__ == '__main__': for test in tests: - print("{} - hash_loginbase -> {}".format(test, hash_loginbase(test))) + print(("{} - hash_loginbase -> {}".format(test, hash_loginbase(test)))) diff --git a/sfa/rspecs/elements/versions/iotlabv1Sliver.py b/sfa/rspecs/elements/versions/iotlabv1Sliver.py index 0f9fb014..269de566 100644 --- a/sfa/rspecs/elements/versions/iotlabv1Sliver.py +++ b/sfa/rspecs/elements/versions/iotlabv1Sliver.py @@ -1,3 +1,5 @@ +from __future__ import print_function + from sfa.rspecs.elements.element import Element from sfa.rspecs.elements.sliver import Sliver @@ -50,7 +52,7 @@ class Iotlabv1Sliver: sliver['type'] = sliver_elem.attrib['name'] #sliver['images'] = Iotlabv1DiskImage.get_images(sliver_elem) - print>>sys.stderr, "\r\n \r\n SLABV1SLIVER.PY \t\t\t get_slivers sliver %s " %( sliver) + print("\r\n \r\n SLABV1SLIVER.PY \t\t\t get_slivers sliver %s " %( sliver), file=sys.stderr) slivers.append(sliver) return slivers diff --git a/sfa/rspecs/pg_rspec_converter.py b/sfa/rspecs/pg_rspec_converter.py index b39184a5..234465f1 100755 --- a/sfa/rspecs/pg_rspec_converter.py +++ b/sfa/rspecs/pg_rspec_converter.py @@ -1,4 +1,6 @@ #!/usr/bin/python +from __future__ import print_function + from lxml import etree from StringIO import StringIO from sfa.util.xrn import Xrn, urn_to_hrn @@ -91,4 +93,4 @@ class PGRSpecConverter: if __name__ == '__main__': import sys if len(sys.argv) > 1: - print PGRSpecConverter.to_sfa_rspec(sys.argv[1]) + print(PGRSpecConverter.to_sfa_rspec(sys.argv[1])) diff --git a/sfa/rspecs/rspec_converter.py b/sfa/rspecs/rspec_converter.py index 7dff2f0b..5d7bdd61 100755 --- a/sfa/rspecs/rspec_converter.py +++ b/sfa/rspecs/rspec_converter.py @@ -1,5 +1,7 @@ #!/usr/bin/python +from __future__ import print_function + from sfa.rspecs.pg_rspec_converter import PGRSpecConverter from sfa.rspecs.sfa_rspec_converter import SfaRSpecConverter from sfa.rspecs.rspec import RSpec @@ -39,8 +41,8 @@ if __name__ == '__main__': pg_rspec = 'test/protogeni.rspec' sfa_rspec = 'test/nodes.rspec' - print "converting pg rspec to sfa rspec" - print RSpecConverter.to_sfa_rspec(pg_rspec) + print("converting pg rspec to sfa rspec") + print(RSpecConverter.to_sfa_rspec(pg_rspec)) - print "converting sfa rspec to pg rspec" - print RSpecConverter.to_pg_rspec(sfa_rspec) + print("converting sfa rspec to pg rspec") + print(RSpecConverter.to_pg_rspec(sfa_rspec)) diff --git a/sfa/rspecs/sfa_rspec_converter.py b/sfa/rspecs/sfa_rspec_converter.py index 7bcc7878..577b788d 100755 --- a/sfa/rspecs/sfa_rspec_converter.py +++ b/sfa/rspecs/sfa_rspec_converter.py @@ -1,5 +1,7 @@ #!/usr/bin/python +from __future__ import print_function + from sfa.util.xrn import hrn_to_urn from sfa.rspecs.rspec import RSpec from sfa.rspecs.version_manager import VersionManager @@ -83,4 +85,4 @@ class SfaRSpecConverter: if __name__ == '__main__': import sys if len(sys.argv) > 1: - print SfaRSpecConverter.to_pg_rspec(sys.argv[1]) + print(SfaRSpecConverter.to_pg_rspec(sys.argv[1])) diff --git a/sfa/rspecs/version_manager.py b/sfa/rspecs/version_manager.py index 9efabeab..cedd54f1 100644 --- a/sfa/rspecs/version_manager.py +++ b/sfa/rspecs/version_manager.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import os from sfa.util.faults import InvalidRSpec, UnsupportedRSpecVersion from sfa.rspecs.version import RSpecVersion @@ -78,19 +80,19 @@ class VersionManager: def show_by_string(self, string): try: - print self.get_version(string) + print(self.get_version(string)) except Exception as e: - print e + print(e) def show_by_schema(self, string): try: - print self.get_version_by_schema(string) + print(self.get_version_by_schema(string)) except Exception as e: - print e + print(e) if __name__ == '__main__': manager = VersionManager() - print manager + print(manager) manager.show_by_string('sfa 1') manager.show_by_string('protogeni 2') manager.show_by_string('protogeni 2 advertisement') diff --git a/sfa/rspecs/versions/iotlabv1.py b/sfa/rspecs/versions/iotlabv1.py index ad491571..856f7787 100644 --- a/sfa/rspecs/versions/iotlabv1.py +++ b/sfa/rspecs/versions/iotlabv1.py @@ -1,3 +1,5 @@ +from __future__ import print_function + from copy import deepcopy @@ -78,10 +80,10 @@ class Iotlabv1(RSpecVersion): # Slivers def get_sliver_attributes(self, hostname, node, network=None): - print>>sys.stderr, "\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes hostname %s " %(hostname) + print("\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes hostname %s " %(hostname), file=sys.stderr) nodes = self.get_nodes({'component_id': '*%s*' %hostname}) attribs = [] - print>>sys.stderr, "\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes-----------------nodes %s " %(nodes) + print("\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes-----------------nodes %s " %(nodes), file=sys.stderr) if nodes is not None and isinstance(nodes, list) and len(nodes) > 0: node = nodes[0] #if node : @@ -93,7 +95,7 @@ class Iotlabv1(RSpecVersion): sliver = sliver[0] attribs = sliver #attribs = self.attributes_list(sliver) - print>>sys.stderr, "\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes----------NN------- sliver %s self.namespaces %s attribs %s " %(sliver, self.namespaces,attribs) + print("\r\n \r\n \r\n \t\t SLABV1.PY get_sliver_attributes----------NN------- sliver %s self.namespaces %s attribs %s " %(sliver, self.namespaces,attribs), file=sys.stderr) return attribs def get_slice_attributes(self, network=None): @@ -143,7 +145,7 @@ class Iotlabv1(RSpecVersion): if attributes is None: attributes=[] # all nodes hould already be present in the rspec. Remove all # nodes that done have slivers - print>>sys.stderr, "\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers ----->get_node " + print("\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers ----->get_node ", file=sys.stderr) for hostname in hostnames: node_elems = self.get_nodes({'component_id': '*%s*' % hostname}) if not node_elems: @@ -163,7 +165,7 @@ class Iotlabv1(RSpecVersion): continue sliver = {'type': requested_sliver_type, 'pl_tags': attributes} - print>>sys.stderr, "\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers node_elem %s sliver_type %s \r\n \r\n " %(node_elem, sliver_type) + print("\r\n \r\n \r\n \t\t\t Iotlabv1.PY add_slivers node_elem %s sliver_type %s \r\n \r\n " %(node_elem, sliver_type), file=sys.stderr) # remove available element for available_elem in node_elem.xpath('./default:available | ./available'): node_elem.remove(available_elem) @@ -303,4 +305,4 @@ if __name__ == '__main__': r = RSpec('/tmp/iotlab.rspec') r.load_rspec_elements(Iotlabv1.elements) r.namespaces = Iotlabv1.namespaces - print r.get(RSpecElements.NODE) + print(r.get(RSpecElements.NODE)) diff --git a/sfa/rspecs/versions/nitosv1.py b/sfa/rspecs/versions/nitosv1.py index 3288b48b..60caf1d1 100644 --- a/sfa/rspecs/versions/nitosv1.py +++ b/sfa/rspecs/versions/nitosv1.py @@ -1,3 +1,5 @@ +from __future__ import print_function + from copy import deepcopy from lxml import etree @@ -237,4 +239,4 @@ if __name__ == '__main__': from sfa.rspecs.rspec_elements import * r = RSpec('/tmp/resources.rspec') r.load_rspec_elements(SFAv1.elements) - print r.get(RSpecElements.NODE) + print(r.get(RSpecElements.NODE)) diff --git a/sfa/rspecs/versions/ofeliav1.py b/sfa/rspecs/versions/ofeliav1.py index d074694b..ff4ae42e 100755 --- a/sfa/rspecs/versions/ofeliav1.py +++ b/sfa/rspecs/versions/ofeliav1.py @@ -1,5 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +from __future__ import print_function + from copy import deepcopy from lxml import etree @@ -231,7 +233,7 @@ if __name__ == '__main__': import pprint from sfa.rspecs.rspec import RSpec from sfa.rspecs.rspec_elements import * - print "main ofeliav1" + print("main ofeliav1") if len(sys.argv)!=2: r = RSpec('/tmp/resources.rspec') else: diff --git a/sfa/rspecs/versions/pgv2.py b/sfa/rspecs/versions/pgv2.py index 01a31550..bdbae4a4 100644 --- a/sfa/rspecs/versions/pgv2.py +++ b/sfa/rspecs/versions/pgv2.py @@ -1,3 +1,5 @@ +from __future__ import print_function + from copy import deepcopy from StringIO import StringIO from sfa.util.xrn import Xrn @@ -262,4 +264,4 @@ if __name__ == '__main__': r = RSpec('/tmp/pg.rspec') r.load_rspec_elements(PGv2.elements) r.namespaces = PGv2.namespaces - print r.get(RSpecElements.NODE) + print(r.get(RSpecElements.NODE)) diff --git a/sfa/rspecs/versions/sfav1.py b/sfa/rspecs/versions/sfav1.py index 6e973e7e..645a6604 100644 --- a/sfa/rspecs/versions/sfav1.py +++ b/sfa/rspecs/versions/sfav1.py @@ -1,3 +1,5 @@ +from __future__ import print_function + from copy import deepcopy from lxml import etree @@ -239,4 +241,4 @@ if __name__ == '__main__': from sfa.rspecs.rspec_elements import * r = RSpec('/tmp/resources.rspec') r.load_rspec_elements(SFAv1.elements) - print r.get(RSpecElements.NODE) + print(r.get(RSpecElements.NODE)) diff --git a/sfa/server/sfa_component_setup.py b/sfa/server/sfa_component_setup.py index f75f1ca7..e35a40a6 100755 --- a/sfa/server/sfa_component_setup.py +++ b/sfa/server/sfa_component_setup.py @@ -1,4 +1,6 @@ #!/usr/bin/python +from __future__ import print_function + import sys import os import tempfile @@ -24,7 +26,7 @@ def handle_gid_mismatch_exception(f): try: return f(*args, **kwds) except ConnectionKeyGIDMismatch: # clean regen server keypair and try again - print "cleaning keys and trying again" + print("cleaning keys and trying again") clean_key_cred() return f(args, kwds) @@ -48,7 +50,7 @@ def server_proxy(url=None, port=None, keyfile=None, certfile=None,verbose=False) url = "http://%(addr)s:%(port)s" % locals() if verbose: - print "Contacting registry at: %(url)s" % locals() + print("Contacting registry at: %(url)s" % locals()) server = SfaServerProxy(url, keyfile, certfile) return server @@ -125,11 +127,11 @@ def GetCredential(registry=None, force=False, verbose=False): # check for existing credential if not force and os.path.exists(credfile): if verbose: - print "Loading Credential from %(credfile)s " % locals() + print("Loading Credential from %(credfile)s " % locals()) cred = Credential(filename=credfile).save_to_string(save_parents=True) else: if verbose: - print "Getting credential from registry" + print("Getting credential from registry") # make sure node private key exists node_pkey_file = config_dir + os.sep + "node.key" node_gid_file = config_dir + os.sep + "node.gid" @@ -177,7 +179,7 @@ def get_trusted_certs(registry=None, verbose=False): registry = server_proxy(url=registry, keyfile=keyfile, certfile=certfile) # get the trusted certs and save them in the right place if verbose: - print "Getting trusted certs from registry" + print("Getting trusted certs from registry") trusted_certs = registry.get_trusted_certs(cred) trusted_gid_names = [] for gid_str in trusted_certs: @@ -187,7 +189,7 @@ def get_trusted_certs(registry=None, verbose=False): trusted_gid_names.append(relative_filename) gid_filename = trusted_certs_dir + os.sep + relative_filename if verbose: - print "Writing GID for %s as %s" % (gid.get_hrn(), gid_filename) + print("Writing GID for %s as %s" % (gid.get_hrn(), gid_filename)) gid.save_to_file(gid_filename, save_parents=True) # remove old certs @@ -195,7 +197,7 @@ def get_trusted_certs(registry=None, verbose=False): for gid_name in all_gids_names: if gid_name not in trusted_gid_names: if verbose: - print "Removing old gid ", gid_name + print("Removing old gid ", gid_name) os.unlink(trusted_certs_dir + os.sep + gid_name) @handle_gid_mismatch_exception @@ -222,7 +224,7 @@ def get_gids(registry=None, verbose=False): registry = server_proxy(url=registry, keyfile=keyfile, certfile=certfile) if verbose: - print "Getting current slices on this node" + print("Getting current slices on this node") # get a list of slices on this node from sfa.generic import Generic generic=Generic.the_flavour() @@ -247,7 +249,7 @@ def get_gids(registry=None, verbose=False): return if verbose: - print "Getting gids for slices on this node from registry" + print("Getting gids for slices on this node from registry") # get the gids # and save them in the right palce records = registry.GetGids(hrns, cred) @@ -265,12 +267,12 @@ def get_gids(registry=None, verbose=False): gid = record['gid'] slice_gid_filename = os.sep.join([vserver_path, "etc", "slice.gid"]) if verbose: - print "Saving GID for %(slicename)s as %(slice_gid_filename)s" % locals() + print("Saving GID for %(slicename)s as %(slice_gid_filename)s" % locals()) GID(string=gid).save_to_file(slice_gid_filename, save_parents=True) # save the node gid in /etc/sfa node_gid_filename = os.sep.join([vserver_path, "etc", "node.gid"]) if verbose: - print "Saving node GID for %(slicename)s as %(node_gid_filename)s" % locals() + print("Saving node GID for %(slicename)s as %(node_gid_filename)s" % locals()) node_gid.save_to_file(node_gid_filename, save_parents=True) @@ -279,15 +281,15 @@ def dispatch(options, args): create_default_dirs() if options.key: if options.verbose: - print "Getting the component's pkey" + print("Getting the component's pkey") get_node_key(registry=options.registry, verbose=options.verbose) if options.certs: if options.verbose: - print "Getting the component's trusted certs" + print("Getting the component's trusted certs") get_trusted_certs(verbose=options.verbose) if options.gids: if options.verbose: - print "Geting the component's GIDs" + print("Geting the component's GIDs") get_gids(verbose=options.verbose) def main(): diff --git a/sfa/storage/dbschema.py b/sfa/storage/dbschema.py index 4c99fb2b..5166b93c 100644 --- a/sfa/storage/dbschema.py +++ b/sfa/storage/dbschema.py @@ -1,3 +1,5 @@ +from __future__ import print_function + import sys import traceback @@ -62,10 +64,10 @@ class DBSchema: def drop_table (self, tablename): if self.table_exists (tablename): - print >>sys.stderr, "%s: Dropping table %s"%(DBSchema.header,tablename) + print("%s: Dropping table %s"%(DBSchema.header,tablename), file=sys.stderr) self.engine.execute ("drop table %s cascade"%tablename) else: - print >>sys.stderr, "%s: no need to drop table %s"%(DBSchema.header,tablename) + print("%s: no need to drop table %s"%(DBSchema.header,tablename), file=sys.stderr) def handle_old_releases (self): try: @@ -75,7 +77,7 @@ class DBSchema: # (.) we've just created the db, so it's either a fresh install, or # (.) we come from a 'very old' depl. # in either case, an import is required but there's nothing to clean up - print >> sys.stderr,"%s: make sure to run import"%(DBSchema.header,) + print("%s: make sure to run import"%(DBSchema.header,), file=sys.stderr) elif self.table_exists ('sfa_db_version'): # we come from an 'old' version self.drop_table ('records') @@ -85,7 +87,7 @@ class DBSchema: # we should be good here pass except: - print >> sys.stderr, "%s: unknown exception"%(DBSchema.header,) + print("%s: unknown exception"%(DBSchema.header,), file=sys.stderr) traceback.print_exc () # after this call the db schema and the version as known by migrate should diff --git a/sfa/storage/record.py b/sfa/storage/record.py index 8600723a..3a9c3159 100644 --- a/sfa/storage/record.py +++ b/sfa/storage/record.py @@ -1,3 +1,5 @@ +from __future__ import print_function + from sfa.util.sfatime import utcparse, datetime_to_string from types import StringTypes from datetime import datetime @@ -82,15 +84,15 @@ class Record: if format == 'text': self.dump_text(dump_parents,sort=sort) elif format == 'xml': - print self.save_as_xml() + print(self.save_as_xml()) elif format == 'simple': - print self.dump_simple() + print(self.dump_simple()) else: raise Exception, "Invalid format %s" % format def dump_text(self, dump_parents=False, sort=False): - print 40*'=' - print "RECORD" + print(40*'=') + print("RECORD") # print remaining fields fields = self.fields() if sort: fields.sort() @@ -102,12 +104,12 @@ class Record: if callable (attrib): continue # handle gid if attrib_name == 'gid': - print " gid:" - print GID(string=attrib).dump_string(8, dump_parents) + print(" gid:") + print(GID(string=attrib).dump_string(8, dump_parents)) elif attrib_name in ['date created', 'last updated']: - print " %s: %s" % (attrib_name, self.date_repr(attrib_name)) + print(" %s: %s" % (attrib_name, self.date_repr(attrib_name))) else: - print " %s: %s" % (attrib_name, attrib) + print(" %s: %s" % (attrib_name, attrib)) def dump_simple(self): return "%s"%self diff --git a/sfa/trust/abac_credential.py b/sfa/trust/abac_credential.py index f454d18a..69ab1051 100644 --- a/sfa/trust/abac_credential.py +++ b/sfa/trust/abac_credential.py @@ -21,6 +21,8 @@ # IN THE WORK. #---------------------------------------------------------------------- +from __future__ import print_function + from sfa.trust.credential import Credential, append_sub, DEFAULT_CREDENTIAL_LIFETIME from sfa.util.sfalogging import logger from sfa.util.sfatime import SFATIME_FORMAT @@ -179,7 +181,7 @@ class ABACCredential(Credential): result += "\nEnd XML\n" except: import traceback - print "exc. Credential.dump_string / XML" + print("exc. Credential.dump_string / XML") traceback.print_exc() return result diff --git a/sfa/trust/certificate.py b/sfa/trust/certificate.py index ff6534e0..6b1e2603 100644 --- a/sfa/trust/certificate.py +++ b/sfa/trust/certificate.py @@ -35,6 +35,8 @@ ## # +from __future__ import print_function + import functools import os import tempfile @@ -280,7 +282,7 @@ class Keypair: return getattr(self,'filename',None) def dump (self, *args, **kwargs): - print self.dump_string(*args, **kwargs) + print(self.dump_string(*args, **kwargs)) def dump_string (self): result="" @@ -837,7 +839,7 @@ class Certificate: return getattr(self,'filename',None) def dump (self, *args, **kwargs): - print self.dump_string(*args, **kwargs) + print(self.dump_string(*args, **kwargs)) def dump_string (self,show_extensions=False): result = "" diff --git a/sfa/trust/credential.py b/sfa/trust/credential.py index f61601a0..ae2cc8d2 100644 --- a/sfa/trust/credential.py +++ b/sfa/trust/credential.py @@ -26,6 +26,8 @@ # Credentials are signed XML files that assign a subject gid privileges to an object gid ## +from __future__ import print_function + import os, os.path import subprocess from types import StringTypes @@ -1154,7 +1156,7 @@ class Credential(object): # # @param dump_parents If true, also dump the parent certificates def dump (self, *args, **kwargs): - print self.dump_string(*args, **kwargs) + print(self.dump_string(*args, **kwargs)) # SFA code ignores show_xml and disables printing the cred xml def dump_string(self, dump_parents=False, show_xml=False): @@ -1197,7 +1199,7 @@ class Credential(object): result += "\nEnd XML\n" except: import traceback - print "exc. Credential.dump_string / XML" + print("exc. Credential.dump_string / XML") traceback.print_exc() return result diff --git a/sfa/trust/credential_factory.py b/sfa/trust/credential_factory.py index 47ddc662..ef738af3 100644 --- a/sfa/trust/credential_factory.py +++ b/sfa/trust/credential_factory.py @@ -21,6 +21,8 @@ # IN THE WORK. #---------------------------------------------------------------------- +from __future__ import print_function + from sfa.util.sfalogging import logger from sfa.trust.credential import Credential from sfa.trust.abac_credential import ABACCredential @@ -103,8 +105,8 @@ if __name__ == "__main__": cred1 = CredentialFactory.createCred(credFile='/tmp/cred.xml') cred2 = CredentialFactory.createCred(credString=c2) - print "C1 = %s" % cred1 - print "C2 = %s" % cred2 + print("C1 = %s" % cred1) + print("C2 = %s" % cred2) c1s = cred1.dump_string() - print "C1 = %s" % c1s + print("C1 = %s" % c1s) # print "C2 = %s" % cred2.dump_string() diff --git a/sfa/trust/gid.py b/sfa/trust/gid.py index 6e668fae..b7fad178 100644 --- a/sfa/trust/gid.py +++ b/sfa/trust/gid.py @@ -25,6 +25,8 @@ # descendant of the certificate class. ## +from __future__ import print_function + import xmlrpclib import uuid @@ -201,7 +203,7 @@ class GID(Certificate): # @param dump_parents If true, also dump the parents of the GID def dump(self, *args, **kwargs): - print self.dump_string(*args,**kwargs) + print(self.dump_string(*args,**kwargs)) def dump_string(self, indent=0, dump_parents=False): result=" "*(indent-2) + "GID\n" diff --git a/sfa/trust/sfaticket.py b/sfa/trust/sfaticket.py index bc8584b4..78e6d878 100644 --- a/sfa/trust/sfaticket.py +++ b/sfa/trust/sfaticket.py @@ -24,6 +24,8 @@ # implements SFA tickets # +from __future__ import print_function + import xmlrpclib from sfa.trust.certificate import Certificate @@ -124,25 +126,25 @@ class SfaTicket(Certificate): self.gidObject = None def dump(self, dump_parents=False): - print "TICKET", self.get_subject() + print("TICKET", self.get_subject()) - print " gidCaller:" + print(" gidCaller:") gidCaller = self.get_gid_caller() if gidCaller: gidCaller.dump(8, dump_parents) - print " gidObject:" + print(" gidObject:") gidObject = self.get_gid_object() if gidObject: gidObject.dump(8, dump_parents) - print " attributes:" + print(" attributes:") for attrname in self.get_attributes().keys(): - print " ", attrname, self.get_attributes()[attrname] + print(" ", attrname, self.get_attributes()[attrname]) - print " rspec:" - print " ", self.get_rspec() + print(" rspec:") + print(" ", self.get_rspec()) if self.parent and dump_parents: - print "PARENT", + print("PARENT", end=' ') self.parent.dump(dump_parents) diff --git a/sfa/util/prefixTree.py b/sfa/util/prefixTree.py index 93b0c5cd..0d7a557e 100755 --- a/sfa/util/prefixTree.py +++ b/sfa/util/prefixTree.py @@ -1,3 +1,5 @@ +from __future__ import print_function + class prefixNode: def __init__(self, prefix): @@ -88,10 +90,10 @@ class prefixTree: """ if not node: node = self.root - print node.prefix + print(node.prefix) for child in node.children: - print child.prefix, + print(child.prefix, end=' ') for child in node.children: self.dump(child) diff --git a/sfa/util/sfalogging.py b/sfa/util/sfalogging.py index 361a2434..2b73b48d 100644 --- a/sfa/util/sfalogging.py +++ b/sfa/util/sfalogging.py @@ -23,6 +23,8 @@ # IN THE WORK. #---------------------------------------------------------------------- +from __future__ import print_function + import os, sys import traceback import logging, logging.handlers @@ -183,14 +185,14 @@ def profile(logger): if __name__ == '__main__': - print 'testing sfalogging into logger.log' + print('testing sfalogging into logger.log') logger1=_SfaLogger('logger.log', loggername='std(info)') logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR) logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG) for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]: - print "====================",msg, logger.logger.handlers + print("====================",msg, logger.logger.handlers) logger.enable_console() logger.critical("logger.critical") diff --git a/sfa/util/sfatime.py b/sfa/util/sfatime.py index 75a2e4a3..3500b2b1 100644 --- a/sfa/util/sfatime.py +++ b/sfa/util/sfatime.py @@ -20,6 +20,8 @@ # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS # IN THE WORK. #---------------------------------------------------------------------- +from __future__ import print_function + from types import StringTypes import time import datetime @@ -98,9 +100,9 @@ def add_datetime(input, days=0, hours=0, minutes=0, seconds=0): if __name__ == '__main__': # checking consistency - print 20*'X' - print ("Should be close to zero: %s"%(datetime_to_epoch(datetime.datetime.utcnow())-time.time())) - print 20*'X' + print(20*'X') + print(("Should be close to zero: %s"%(datetime_to_epoch(datetime.datetime.utcnow())-time.time()))) + print(20*'X') for input in [ '+2d', '+3w', @@ -112,4 +114,4 @@ if __name__ == '__main__': '2014-05-28T15:18', '2014-05-28T15:18:30', ]: - print "input=%20s -> parsed %s"%(input,datetime_to_string(utcparse(input))) + print("input=%20s -> parsed %s"%(input,datetime_to_string(utcparse(input))))