[transmageddon] Port to Python3



commit 727225b36b2b96c2ffe1292ad8b0bf5ca2729c28
Author: Christian Fredrik Kalager Schaller <uraeus linuxrisin org>
Date:   Sun Sep 16 18:31:23 2012 +0200

    Port to Python3

 bin/transmageddon.in     |    2 +-
 src/codecfinder.py       |    6 ++--
 src/presets.py           |   16 ++++++------
 src/transcoder_engine.py |    8 +++---
 src/transmageddon.py     |   63 ++++++++++++++++++---------------------------
 src/which.py             |   18 ++++++------
 transmageddon.spec.in    |    5 +--
 7 files changed, 52 insertions(+), 66 deletions(-)
---
diff --git a/bin/transmageddon.in b/bin/transmageddon.in
index 6f07c05..4fafff5 100644
--- a/bin/transmageddon.in
+++ b/bin/transmageddon.in
@@ -1,3 +1,3 @@
 #!/bin/bash
 cd @DATADIR@/transmageddon
-python transmageddon.py
+python3 transmageddon.py
diff --git a/src/codecfinder.py b/src/codecfinder.py
index 44e6fde..ed13166 100644
--- a/src/codecfinder.py
+++ b/src/codecfinder.py
@@ -131,7 +131,7 @@ def get_muxer_element(containercaps):
        if Gst.ElementFactory.list_is_type(fact, 16):
            muxers.append(fact.get_name())
            features.append(fact)
-   muxerfeature = dict(zip(muxers, features))
+   muxerfeature = dict(list(zip(muxers, features)))
    incomingcaps = Gst.caps_from_string(containercaps)
    # print "incomingcaps is " + str(containercaps)
    for muxer in muxers:
@@ -183,7 +183,7 @@ def get_audio_encoder_element(audioencodercaps):
                if fact.get_name() != 'encodebin':
                    encoders.append(fact.get_name())
                    features.append(fact)
-   encoderfeature = dict(zip(encoders, features))
+   encoderfeature = dict(list(zip(encoders, features)))
    
    if isinstance(audioencodercaps, str): # this value should always be a caps value, so this sometimes being a string is a bug
        incomingcaps = Gst.caps_from_string(audioencodercaps)
@@ -236,7 +236,7 @@ def get_video_encoder_element(videoencodercaps):
        #        fact.get_metadata().split('/')):
        #    encoders.append(fact.get_name())
        #   features.append(fact)
-   encoderfeature = dict(zip(encoders, features))
+   encoderfeature = dict(list(zip(encoders, features)))
    # print "videoencodercaps is " + str(videoencodercaps)
    incomingcaps = videoencodercaps
    for x in encoders:
diff --git a/src/presets.py b/src/presets.py
index 2086e2a..ed39890 100644
--- a/src/presets.py
+++ b/src/presets.py
@@ -41,7 +41,7 @@ import gettext
 import logging
 import os
 import sys
-import urllib2
+import urllib.request, urllib.error, urllib.parse
 import xml.etree.ElementTree
 import gstfraction
 
@@ -452,7 +452,7 @@ def version_info():
     """
     info = ""
     
-    for name, device in _presets.items():
+    for name, device in list(_presets.items()):
         info += "%s, %s\n" % (name, device.version)
         
     return info
@@ -482,13 +482,13 @@ def install_preset(location, name):
         })
         
         try:
-            f = urllib2.urlopen(path)
+            f = urllib.request.urlopen(path)
             local_file = os.path.join(local_path, ".".join([name, ext]))
             _log.debug(_("Writing to %(file)s") % {
                 "file": local_file,
             })
             open(local_file, "w").write(f.read())
-        except Exception, e:
+        except Exception as e:
             _log.error(_("There was an error fetching and installing " \
                          "%(location)s: %(error)s") % {
                 "location": path,
@@ -513,7 +513,7 @@ def check_for_updates(location = UPDATE_LOCATION):
     if not location.endswith("/"):
         location = location + "/"
     
-    f = urllib2.urlopen(location + "presets.txt")
+    f = urllib.request.urlopen(location + "presets.txt")
     
     try:
         for line in f.readlines():
@@ -524,7 +524,7 @@ def check_for_updates(location = UPDATE_LOCATION):
             
             if len(parts) == 2:
                 name, version = parts
-                if _presets.has_key(name):
+                if name in _presets:
                     if _presets[name].version >= version:
                         _log.debug(_("Device preset %(name)s is up to date") % {
                             "name": name,
@@ -535,7 +535,7 @@ def check_for_updates(location = UPDATE_LOCATION):
                         })
                         try:
                             updates.append((location, name))
-                        except Exception, e:
+                        except Exception as e:
                             _log.error(_("Error installing preset %(name)s " \
                                          "from %(location)s: %(error)s") % {
                                 "name": name,
@@ -548,7 +548,7 @@ def check_for_updates(location = UPDATE_LOCATION):
                     })
                     try:
                         updates.append((location, name))
-                    except Exception, e:
+                    except Exception as e:
                         _log.error(_("Error installing preset %(name)s " \
                                      "from %(location)s: %(error)s") % {
                             "name": name,
diff --git a/src/transcoder_engine.py b/src/transcoder_engine.py
index 274fa0c..0901a0e 100644
--- a/src/transcoder_engine.py
+++ b/src/transcoder_engine.py
@@ -135,7 +135,7 @@ class Transcoder(GObject.GObject):
                    self.pipeline.add(self.deinterlacer)
    
                    self.deinterlacer.link(self.colorspaceconverter)
-	           self.colorspaceconverter.link(self.videoflipper)
+                   self.colorspaceconverter.link(self.videoflipper)
                    self.deinterlacer.set_state(Gst.State.PAUSED)
                    self.colorspaceconverter.set_state(Gst.State.PAUSED)
                    self.videoflipper.set_state(Gst.State.PAUSED)
@@ -330,10 +330,10 @@ class Transcoder(GObject.GObject):
        mtype = message.type
        # print mtype
        if mtype == Gst.MessageType.ERROR:
-           print "we got an error, life is shit"
+           print("we got an error, life is shit")
            err, debug = message.parse_error()
-           print err 
-           print debug
+           print(err) 
+           print(debug)
            Gst.debug_bin_to_dot_file (self.pipeline, \
            Gst.DebugGraphDetails.ALL, 'transmageddon-debug-graph')
            #self.emit('got-error', err.message)
diff --git a/src/transmageddon.py b/src/transmageddon.py
index 6928713..d07b63d 100644
--- a/src/transmageddon.py
+++ b/src/transmageddon.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
 # -.- coding: utf-8 -.-
 
 # Transmageddon
@@ -35,7 +35,7 @@ from gi.repository import GObject
 GObject.threads_init()
 
 import transcoder_engine
-from urlparse import urlparse
+from urllib.parse import urlparse
 import codecfinder
 import about
 import presets
@@ -46,12 +46,12 @@ import datetime
 
 #major, minor, patch = Gst.pygst_version
 #if (major == 0) and (patch < 22):
-#   print "You need version 0.10.22 or higher of Gstreamer-python for Transmageddon" 
+#   print("You need version 0.10.22 or higher of Gstreamer-python for Transmageddon")
 #   sys.exit(1)
 
 major, minor, patch = GObject.pygobject_version
 if (major == 2) and (minor < 18):
-   print "You need version 2.18.0 or higher of pygobject for Transmageddon"
+   print("You need version 2.18.0 or higher of pygobject for Transmageddon")
    sys.exit(1)
 
 
@@ -194,8 +194,8 @@ class Transmageddon(Gtk.Application):
            os.system(dot + " -Tpng -o " + pngfile + " " + dotfile)
            Gtk.show_uri(self.win.get_screen(), "file://"+pngfile, 0)
        except which.WhichError:
-              print "The debug feature requires graphviz (dot) to be installed."
-              print "Transmageddon can not find the (dot) binary."
+              print("The debug feature requires graphviz (dot) to be installed.")
+              print("Transmageddon can not find the (dot) binary.")
 
    # callback function for "about"
    def about_cb(self, action, parameter):
@@ -206,7 +206,7 @@ class Transmageddon(Gtk.Application):
 
    # callback function for "quit"
    def quit_cb(self, action, parameter):
-        print "You have quit."
+        print("You have quit.")
         self.quit()
 
 class TransmageddonUI(Gtk.ApplicationWindow):
@@ -259,7 +259,6 @@ class TransmageddonUI(Gtk.ApplicationWindow):
                vbox.add(self.videorows[x])
            return vbox
 
-
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("transmageddon")
        uifile = "transmageddon.ui"
@@ -338,7 +337,7 @@ class TransmageddonUI(Gtk.ApplicationWindow):
        self.audiodirectory = \
                    GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC)
        #else:
-       #    print "XDG video or audio directory not available"
+       #    print("XDG video or audio directory not available")
        #    self.videodirectory = os.getenv('HOME')
        #    self.audiodirectory = os.getenv('HOME')
        if self.videodirectory is None:
@@ -361,7 +360,7 @@ class TransmageddonUI(Gtk.ApplicationWindow):
            try:
                self.set_icon_from_file("transmageddon.svg")
            except:
-               print "failed to find appicon"
+               print("failed to find appicon")
 
        # default all but top box to insensitive by default
        # self.containerchoice.set_sensitive(False)
@@ -407,14 +406,14 @@ class TransmageddonUI(Gtk.ApplicationWindow):
        self.p_time = Gst.Format.TIME
 
        # Populate the Container format combobox
-       # print "do we try to populate container choice"
+       # print("do we try to populate container choice")
        for i in supported_containers:
            self.containerchoice.append_text(i)
        # add i18n "No container"option
        self.containerchoice.append_text(_("No container (Audio-only)"))
 
        # Populate the rotatation box
-       # print "populating rotationbox"
+       # print("populating rotationbox")
        self.rotationlist = [_("No rotation (default)"),\
                             _("Clockwise 90 degrees"), \
                             _("Rotate 180 degrees"),
@@ -431,17 +430,17 @@ class TransmageddonUI(Gtk.ApplicationWindow):
        self.rotationvalue = int(0)
       
        # Populate Device Presets combobox
-       # print "starting preset population"
+       # print("starting preset population")
        devicelist = []
        shortname = []
-       preset_list = sorted(presets.get().items(),
+       preset_list = sorted(list(presets.get().items()),
                             key = (lambda x: x[1].make + x[1].model))
        for x, (name, device) in enumerate(preset_list):
            self.presetchoice.append_text(str(device))
            devicelist.append(str(device))
            shortname.append(str(name))
 
-       for (name, device) in (presets.get().items()):
+       for (name, device) in (list(presets.get().items())):
            shortname.append(str(name))
        # self.presetchoices = dict(zip(devicelist, shortname))
        self.presetchoices = shortname
@@ -492,7 +491,7 @@ class TransmageddonUI(Gtk.ApplicationWindow):
        elif preset.container == "video/webm":
            self.containerchoice.set_active(12)
        else:
-            print "failed to set container format from preset data"
+            print("failed to set container format from preset data")
 
 
        # Check for number of passes
@@ -509,22 +508,18 @@ class TransmageddonUI(Gtk.ApplicationWindow):
    # FORMAT_TIME only value implemented by all plugins used
    # a lot of original code from Gst-python synchronizer.py example
    def Increment_Progressbar(self):
-       # print "incrementing progressbar"
+       # print("incrementing progressbar")
        if self.start_time == False:  
            self.start_time = time.time()
        try:
            success, position = \
                    self._transcoder.uridecoder.query_position(Gst.Format.TIME)
-           #print "position is " + str(position)
-           # print "success is " + str(success)
        except:
            position = Gst.CLOCK_TIME_NONE
 
        try:
            success, duration = \
                    self._transcoder.uridecoder.query_duration(Gst.Format.TIME)
-           # print "duration is " + str(duration)
-           # print "success is " + str(success)
        except:
            duration = Gst.CLOCK_TIME_NONE
        if position != Gst.CLOCK_TIME_NONE:
@@ -535,8 +530,6 @@ class TransmageddonUI(Gtk.ApplicationWindow):
                    percent = (value*100)
                    timespent = time.time() - self.start_time
                    percent_remain = (100-percent)
-                   #print "percent remain " + str(percent_remain)
-                   #print "percentage is " + str(percent)
                    if percent != 0:
                        rem = (timespent / percent) * percent_remain
                    else: 
@@ -569,7 +562,6 @@ class TransmageddonUI(Gtk.ApplicationWindow):
    # use it for the progressbar
    def ProgressBarUpdate(self, source):
        GObject.timeout_add(500, self.Increment_Progressbar)
-       # print "ProgressBar timeout_add startet"
 
    def _on_eos(self, source):
        context_id = self.StatusBar.get_context_id("EOS")
@@ -704,9 +696,9 @@ class TransmageddonUI(Gtk.ApplicationWindow):
                                        str(GstPbutils.pb_utils_get_codec_description   (self.inputvideocaps)),
                                       '</small>')))
        else:
-          print "hoped for a great discovery; got an error"
-          print result
-          print error
+          print("hoped for a great discovery; got an error")
+          print(result)
+          print(error)
 
    def discover(self, path):
        self.discovered.discover_uri_async("file://"+path)
@@ -772,7 +764,6 @@ class TransmageddonUI(Gtk.ApplicationWindow):
                    self.bogus=1
                self.nocontaineroptiontoggle=False
            self.containerchoice.set_sensitive(True)
-       # print "filechoosing done"
 
    def _start_transcoding(self): 
        filechoice = self.builder.get_object ("FileChooser").get_uri()
@@ -819,19 +810,17 @@ class TransmageddonUI(Gtk.ApplicationWindow):
 
    def donemessage(self, donemessage, null):
        if donemessage == GstPbutils.InstallPluginsReturn.SUCCESS:
-           # print "success " + str(donemessage)
            if Gst.update_registry():
-               print "Plugin registry updated, trying again"
+               print("Plugin registry updated, trying again")
            else:
-               print "Gstreamer registry update failed"
+               print("Gstreamer registry update failed")
            if self.containertoggle == False:
-               # print "done installing plugins, starting transcode"
                # FIXME - might want some test here to check plugins needed are
                # actually installed
                # but it is a rather narrow corner case when it fails
                self._start_transcoding()
        elif donemessage == GstPbutils.InstallPluginsReturn.PARTIAL_SUCCESS:
-           print "Plugin install not fully succesfull"
+           print("Plugin install not fully succesfull")
            # self.check_for_elements()
        elif donemessage == GstPbutils.InstallPluginsReturn.NOT_FOUND:
            context_id = self.StatusBar.get_context_id("EOS")
@@ -852,7 +841,6 @@ class TransmageddonUI(Gtk.ApplicationWindow):
            self.transcodebutton.set_sensitive(True)
        else:
            context_id = self.StatusBar.get_context_id("EOS")
-           print donemessage
            self.StatusBar.push(context_id, _("Missing plugin installation failed: "))
 
 
@@ -896,7 +884,6 @@ class TransmageddonUI(Gtk.ApplicationWindow):
                fail_info.append(self.VideoCodec)
            missing = []
            for x in fail_info:
-               print x.to_string()
                missing.append(GstPbutils.missing_encoder_installer_detail_new(x))
            context = GstPbutils.InstallPluginsContext ()
            context.set_xid(self.TopWindow.get_window().get_xid())
@@ -937,14 +924,14 @@ class TransmageddonUI(Gtk.ApplicationWindow):
            self.passcounter=int(1)
            self.StatusBar.push(context_id, (_("Pass %(count)d Progress") % {'count': self.passcounter}))
        if self.haveaudio:
-           if self.audiodata.has_key("samplerate"):
+           if "samplerate" in self.audiodata:
                # self.check_for_elements()
                if self.missingtoggle==False:
                    self._start_transcoding()
            else:
                self.waiting_for_signal="True"
        elif self.havevideo:
-           if self.videodata.has_key("videoheight"):
+           if "videoheight" in self.videodata:
                # self.check_for_elements()
                if self.missingtoggle==False:
                    self._start_transcoding()
@@ -971,7 +958,7 @@ class TransmageddonUI(Gtk.ApplicationWindow):
        # self.audiocodecs - contains list of whats in self.audiorows
        # self.videocodecs - contains listof whats in self.videorows
        # audio_codecs, video_codecs - temporary lists
-       # print "trying to populate menu choices"
+
        # clean up stuff from previous run
        self.houseclean=True # set this to avoid triggering events when cleaning out menus
        for c in self.audiocodecs: # 
diff --git a/src/which.py b/src/which.py
index 64de60d..e7f91c1 100644
--- a/src/which.py
+++ b/src/which.py
@@ -113,13 +113,13 @@ def _getRegisteredExecutable(exeName):
     if sys.platform.startswith('win'):
         if os.path.splitext(exeName)[1].lower() != '.exe':
             exeName += '.exe'
-        import _winreg
+        import winreg
         try:
             key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" +\
                   exeName
-            value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)
+            value = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, key)
             registered = (value, "from HKLM\\"+key)
-        except _winreg.error:
+        except winreg.error:
             pass
         if registered and not os.path.exists(registered[0]):
             registered = None
@@ -266,7 +266,7 @@ def which(command, path=None, verbose=0, exts=None):
     If no match is found for the command, a WhichError is raised.
     """
     try:
-        match = whichgen(command, path, verbose, exts).next()
+        match = next(whichgen(command, path, verbose, exts))
     except StopIteration:
         raise WhichError("Could not find '%s' on the path." % command)
     return match
@@ -303,17 +303,17 @@ def main(argv):
     try:
         optlist, args = getopt.getopt(argv[1:], 'haVvqp:e:',
             ['help', 'all', 'version', 'verbose', 'quiet', 'path=', 'exts='])
-    except getopt.GetoptError, msg:
+    except getopt.GetoptError as msg:
         sys.stderr.write("which: error: %s. Your invocation was: %s\n"\
                          % (msg, argv))
         sys.stderr.write("Try 'which --help'.\n")
         return 1
     for opt, optarg in optlist:
         if opt in ('-h', '--help'):
-            print _cmdlnUsage
+            print(_cmdlnUsage)
             return 0
         elif opt in ('-V', '--version'):
-            print "which %s" % __version__
+            print("which %s" % __version__)
             return 0
         elif opt in ('-a', '--all'):
             all = 1
@@ -341,9 +341,9 @@ def main(argv):
         nmatches = 0
         for match in whichgen(arg, path=altpath, verbose=verbose, exts=exts):
             if verbose:
-                print "%s (%s)" % match
+                print("%s (%s)" % match)
             else:
-                print match
+                print(match)
             nmatches += 1
             if not all:
                 break
diff --git a/transmageddon.spec.in b/transmageddon.spec.in
index 84599ba..4659190 100644
--- a/transmageddon.spec.in
+++ b/transmageddon.spec.in
@@ -11,13 +11,12 @@ Group:		Applications/Multimedia
 URL:		http://www.linuxrising.org/transmageddon
 BuildRoot:      %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)
 
-Requires:	python >= 2.5
+Requires:	python3
 Requires:	gstreamer1 >= @GST_REQ@
 Requires:       notify-python
-Requires:	pygobject3
+Requires:	python-gobject
 
 BuildRequires:	gstreamer1-devel >= @GST_REQ@
-BuildRequires:	python-devel >= 2.3
 BuildRequires:  gettext
 BuildRequires:  desktop-file-utils
 BuildRequires:  intltool



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]