Projet

Général

Profil

Révision 5301b7f5

ID5301b7f5d5a5e0132bf3064aa40df57bee9d7492
Parent 51864405
Enfant 4a6d44a4

Ajouté par Lars Kruse il y a environ 5 ans

Plugin deb_packages: prepare migration to Python3

Voir les différences:

plugins/apt/deb_packages/deb_packages.py
27 27
BUG: If a package will be upgraded, and brings in new dependencies,
28 28
     these new deps will not be counted. WONTFIX
29 29
"""
30

  
31
from __future__ import print_function
32

  
30 33
import sys
31 34
import argparse
32 35
import apt_pkg
......
39 42
from collections  import defaultdict, namedtuple
40 43
from types import StringTypes, TupleType, DictType, ListType, BooleanType
41 44

  
45

  
42 46
class EnvironmentConfigBroken(Exception): pass
43 47

  
44 48
# print environmental things
45
# for k,v in os.environ.iteritems(): print >> sys.stderr, "%r : %r" % (k,v)
49
# for k,v in os.environ.items(): print("%r : %r" % (k,v), file=sys.stderr)
46 50

  
47 51
def getEnv(name, default=None, cast=None):
48 52
    """
......
59 63
        var = default
60 64
    except:
61 65
        # now probably the cast went wrong
62
        print >> sys.stderr, "for environment variable %r, %r is no valid value"%(name, var)
66
        print("for environment variable %r, %r is no valid value" % (name, var), file=sys.stderr)
63 67
        var = default
64 68
    return var
65 69

  
......
217 221
        super(TreeTwig, self).__init__(defaultFactory)
218 222

  
219 223
    def printAsTree(self, indent=0):
220
        for k, tree in self.iteritems():
221
            print "  " * indent, repr(k)
224
        for k, tree in self.items():
225
            print("  " * indent, repr(k))
222 226
            if isinstance(tree, TreeTwig):
223 227
                printTree(tree, indent+1)
224 228
            else:
225
                print tree
229
                print(tree)
226 230

  
227 231
    def printAsLine(self):
228
        print self.asLine()
232
        print(self.asLine())
229 233

  
230 234
    def asLine(self):
231 235
        values = ""
232
        for key, residue in self.iteritems():
236
        for key, residue in self.items():
233 237
            if residue:
234 238
                values += " %r" % key
235 239
                if isinstance(residue, TreeTwig):
......
310 314
        d = t
311 315
        for key in keys:
312 316
            if not key:
313
                print f
317
                print(f)
314 318
            dKey = f.__getattribute__(key)
315 319
            d = d[dKey]
316 320
    return t
......
504 508
               "graph_vlabel packages".format(**d)
505 509

  
506 510
    def printConfig(self):
507
        print self.configHead()
511
        print(self.configHead())
508 512
        for options, item in self.options_sorted:
509 513
            if not self.packetHandler.includeNow and self.optionIsDpkgStatus(details=options):
510 514
                 continue
511 515
            i = self.configD(options, item)
512
            print "{rrdName}.label {options}".format(**i)
513
            print "{rrdName}.info {info}".format(**i)
514
            print "{rrdName}.draw AREASTACK".format(**i)
516
            print("{rrdName}.label {options}".format(**i))
517
            print("{rrdName}.info {info}".format(**i))
518
            print("{rrdName}.draw AREASTACK".format(**i))
515 519

  
516 520
    def optionIsDpkgStatus(self, details, options=None):
517 521
        """
......
530 534
        return isNow
531 535

  
532 536
    def printValues(self):
533
        print "\nmultigraph packages_{option}_{type}".format(option=self.generate_rrd_name_from(self.option),
534
                                                             type=self.packetHandler.type)
537
        print("\nmultigraph packages_{option}_{type}"
538
              .format(option=self.generate_rrd_name_from(self.option),
539
                      type=self.packetHandler.type))
535 540
        for options, item in self.options_sorted:
536 541
            if not self.packetHandler.includeNow and self.optionIsDpkgStatus(details=options):
537 542
                 continue
538 543
            i = self.configD(options, item)
539 544
            i['value'] = len(self.get(options, []))
540
            print "{rrdName}.value {value}".format(**i)
545
            print("{rrdName}.value {value}".format(**i))
541 546
            self._printExtInfoPackageList(options)
542 547

  
543 548
    def _printExtInfoPackageList(self, options):
......
545 550
        packageList = self[options]
546 551
        packageCount = len( packageList )
547 552
        if 0 < packageCount <= MAX_LIST_SIZE_EXT_INFO:
548
            print "%s.extinfo " % rrdName,
549
            for item in packageList:
550
                print self.packetHandler.extInfoItemString.format(i=item),
551
            print
553
            print("%s.extinfo %s" % (rrdName, " ".join(
554
                self.packetHandler.extInfoItemString.format(i=item) for item in packageList)))
555

  
552 556

  
553 557
packetHandlerD = {}
554 558
""" Dictionary for PacketHandlerclasses with its 'type'-key """
......
644 648
        }
645 649
        self.envConfig = self._envParser()
646 650
        self._envValidater()
647
        # print >> sys.stderr, self.envConfig
651
        # print(self.envConfig, file=sys.stderr)
648 652
        self.statL = []
649 653
        if self.envConfig:
650 654
            for config in self.envConfig:
......
655 659
                                                    extInfo = config['show_ext'])
656 660
                self.statL.append(packageStat)
657 661
        if not self.statL:
658
            print "# no munin config found in environment vars"
662
            print("# no munin config found in environment vars")
659 663

  
660 664
    def execute(self):
661 665
        self.args = self.argParser.parse_args(self.commandLineArgs)
......
715 719
                out =  StringIO.StringIO()
716 720
                sys.stdout = out
717 721
                # run writes now to new sys.stdout
718
                print "# executed at %r (%r)" %(strftime("%s"), strftime("%c"))
722
                print("# executed at %r (%r)" % (strftime("%s"), strftime("%c")))
719 723
                self._run()
720 724
                sys.stdout = stdoutDef
721 725
                # print output to stdout
......
729 733
                    # 'No such file or directory'
730 734
                    os.makedirs( os.path.dirname(CACHE_FILE) )
731 735
                else:
732
                    print sys.stderr.write("%r : %r" % (e, CACHE_FILE))
736
                    sys.stderr.write("%r : %r" % (e, CACHE_FILE))
733 737
            finally:
734 738
                # restore stdout
735 739
                sys.stdout = stdoutDef
736 740
        else:
737 741
            with open(CACHE_FILE,'r') as data:
738
                print data.read()
742
                print(data.read())
739 743

  
740 744
    def _run(self):
741 745
        # p … package
......
760 764
            stat.printConfig()
761 765

  
762 766
    def autoconf(self):
763
        print 'yes'
767
        print('yes')
764 768

  
765 769
    def _argParser(self):
766 770
        parser = argparse.ArgumentParser(description="Show some statistics "\
......
815 819
            elif m.group('res') == 'show_ext':
816 820
                configPart['show_ext'][m.group('optNumber')] = os.getenv(var)
817 821
            else:
818
                print >> sys.stderr, "configuration option %r was ignored" % (var)
822
                print("configuration option %r was ignored" % (var), file=sys.stderr)
819 823
        # we have now dicts for 'sort_by' and 'show_ext' keys
820 824
        # changing them to lists
821 825
        for graphConfig in config.itervalues():
......
830 834
        """
831 835
        for graph in self.envConfig:
832 836
            if graph['type'] not in ('installed', 'upgradable'):
833
                print >> sys.stderr, \
834
                      "GraphType must be 'installed' or 'upgradable' but not %r"%(graph.type), \
835
                      graph
837
                print("GraphType must be 'installed' or 'upgradable' but not %r %s"
838
                      % (graph.type, graph), file=sys.stderr)
836 839
                raise EnvironmentConfigBroken("Environment Config broken")
837 840
            if not graph['sort_by']:
838
                print >> sys.stderr, \
839
                      "Graph must be sorted by anything"
841
                print("Graph must be sorted by anything", file=sys.stderr)
840 842
                raise EnvironmentConfigBroken("Environment Config broken")
841 843
            # check for valid options for sort_by
842 844
            unusableOptions = set(graph['sort_by']) - PackageStat.viewSet
843 845
            if unusableOptions:
844
                print >> sys.stderr, \
845
                      "%r are not valid options for 'sort_by'" % (unusableOptions)
846
                print("%r are not valid options for 'sort_by'" % unusableOptions, file=sys.stderr)
846 847
                raise EnvironmentConfigBroken("Environment Config broken")
847 848
            # check for valid options for sort_by
848 849
            unusableOptions = set(graph['show_ext']) - PackageStat.viewSet
849 850
            if unusableOptions:
850
                print >> sys.stderr, \
851
                      "%r are not valid options for 'show_ext'" % (x)
851
                print("%r are not valid options for 'show_ext'" % x, file=sys.stderr)
852 852
                raise EnvironmentConfigBroken("Environment Config broken")
853 853

  
854 854
if __name__=='__main__':

Formats disponibles : Unified diff