def run(self):
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        err = False
        msg = ''
        message = str(self.topic)
        data = json.dumps(self.publisherKwargs)
        try:
            qs = u'{ "jsonrpc": "2.0", "id": 0, "method": "JSONRPC.NotifyAll", "params": {"sender":"%s", "message":"%s", "data":%s} }' %(self.taskKwargs['jsonnotify'], message, data)
            qs = qs.encode('utf-8', 'ignore')
            json_query = xbmc.executeJSONRPC(qs)
            json_query = unicode(json_query, 'utf-8', 'ignore')
            json_response = json.loads(json_query)
        except Exception:
            e = sys.exc_info()[0]
            err = True
            if hasattr(e, 'message'):
                msg = unicode(e.message)
            msg = msg + u'\n' + unicode(traceback.format_exc())
        else:
            if json_response.has_key('result'):
                if json_response['result'] != u'OK':
                    err = True
                    msg = u'JSON Notify Error %s' % json_response['result']
            else:
                err = True
                msg = u'JSON Notify Error: %s' % unicode(json_response)

        self.threadReturn(err, msg)
Пример #2
0
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        err = False
        msg = ''
        message = str(self.topic)
        data = json.dumps(self.publisherKwargs)
        try:
            qs = u'{ "jsonrpc": "2.0", "id": 0, "method": "JSONRPC.NotifyAll", "params": {"sender":"%s", "message":"%s", "data":%s} }' % (
                self.taskKwargs['jsonnotify'], message, data)
            qs = qs.encode('utf-8', 'ignore')
            json_query = xbmc.executeJSONRPC(qs)
            json_query = str(json_query, 'utf-8', 'ignore')
            json_response = json.loads(json_query)
        except Exception as e:
            err = True
            msg = str(e)
        else:
            if json_response.has_key('result'):
                if json_response['result'] != u'OK':
                    err = True
                    msg = u'JSON Notify Error %s' % json_response['result']
            else:
                err = True
                msg = u'JSON Notify Error: %s' % str(json_response)

        self.threadReturn(err, msg)
Пример #3
0
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        if isinstance(self.runtimeargs, list):
            if len(self.runtimeargs) > 0:
                self.runtimeargs = u''.join(self.runtimeargs)
            else:
                self.runtimeargs = u''
        s = requests.Session()
        url = self.taskKwargs['http'] + self.runtimeargs
        if self.taskKwargs['user'] != '' and self.taskKwargs['pass'] != '':
            s.auth = (self.taskKwargs['user'], self.taskKwargs['pass'])
        if self.taskKwargs['request-type'] == 'POST-GET':
            verb = 'POST'
        else:
            verb = self.taskKwargs['request-type']

        err, msg = self.sendRequest(s, verb, url)

        if self.taskKwargs['request-type'] == 'POST-GET':
            err2, msg2 = self.sendRequest(s, 'GET', url, postget=True)
            err = err or err2
            msg = u'\n'.join([msg, msg2])

        s.close()
        self.threadReturn(err, msg)
Пример #4
0
 def run(self):
     if self.taskKwargs['notify'] is True:
         notify(
             _('Task %s launching for event: %s') %
             (self.taskId, str(self.topic)))
     err = False
     msg = ''
     args = ' %s' % ' '.join(self.runtimeargs)
     # noinspection PyBroadException,PyBroadException,PyBroadException
     try:
         if len(self.runtimeargs) > 0:
             result = xbmc.executebuiltin(
                 '%s, %s' % (self.taskKwargs['builtin'], args))
         else:
             result = xbmc.executebuiltin('%s' % self.taskKwargs['builtin'])
         if result is not None:
             msg = result
             if result != '':
                 err = True
     except Exception:
         e = sys.exc_info()[0]
         err = True
         if hasattr(e, 'message'):
             msg = str(e.message)
         msg = msg + '\n' + traceback.format_exc()
     self.threadReturn(err, msg)
Пример #5
0
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        err = False
        msg = ''
        message = str(self.topic)
        data = str(self.publisherKwargs).replace('\'', '"')
        try:
            json_query = xbmc.executeJSONRPC(
                '{ "jsonrpc": "2.0", "id": 0, "method": "JSONRPC.NotifyAll", "params": {"sender":"%s", "message":"%s", "data":%s} }'
                % (self.taskKwargs['jsonnotify'], message, data))
            json_query = unicode(json_query, 'utf-8', errors='ignore')
            json_response = json.loads(json_query)
        except Exception:
            e = sys.exc_info()[0]
            err = True
            if hasattr(e, 'message'):
                msg = str(e.message)
            msg = msg + '\n' + traceback.format_exc()
        else:
            if json_response.has_key('result'):
                if json_response['result'] != u'OK':
                    err = True
                    msg = 'JSON Notify Error %s' % json_response['result']
            else:
                err = True
                msg = 'JSON Notify Error: %s' % str(json_response)

        self.threadReturn(err, msg)
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        if isinstance(self.runtimeargs, list):
            if len(self.runtimeargs) > 0:
                self.runtimeargs = u''.join(self.runtimeargs)
            else:
                self.runtimeargs = u''
        s = requests.Session()
        url = self.taskKwargs['http']+self.runtimeargs
        if self.taskKwargs['user'] != '' and self.taskKwargs['pass'] != '':
            s.auth = (self.taskKwargs['user'], self.taskKwargs['pass'])
        if self.taskKwargs['request-type'] == 'POST-GET':
            verb = 'POST'
        else:
            verb = self.taskKwargs['request-type']

        err, msg = self.sendRequest(s, verb, url)

        if self.taskKwargs['request-type'] == 'POST-GET':
            err2, msg2 = self.sendRequest(s, 'GET', url, postget=True)
            err = err or err2
            msg = u'\n'.join([msg, msg2])

        s.close()
        self.threadReturn(err, msg)
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        err = False
        msg = ''
        args = self.runtimeargs
        try:
            useImport = self.taskKwargs['import']
        except KeyError:
            useImport = False
        try:
            if len(self.runtimeargs) > 0:
                if useImport is False:
                    args = ' %s' % ' '.join(args)
                    result = xbmc.executebuiltin(
                        'XBMC.RunScript(%s, %s)' %
                        (self.taskKwargs['pythonfile'], args))
                else:
                    directory, module_name = os.path.split(
                        self.taskKwargs['pythonfile'])
                    module_name = os.path.splitext(module_name)[0]

                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name)
                        result = module.run(args)
                    finally:
                        sys.path[:] = path
            else:
                if useImport is False:
                    result = xbmc.executebuiltin('XBMC.RunScript(%s)' %
                                                 self.taskKwargs['pythonfile'])
                else:
                    directory, module_name = os.path.split(
                        self.taskKwargs['pythonfile'])
                    module_name = os.path.splitext(module_name)[0]

                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name)
                        result = module.run(args)
                    finally:
                        sys.path[:] = path
            if result is not None:
                msg = result
                if result != '':
                    err = True
        except Exception:
            e = sys.exc_info()[0]
            err = True
            if hasattr(e, 'message'):
                msg = str(e.message)
            msg = msg + '\n' + traceback.format_exc()

        self.threadReturn(err, msg)
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        err = False
        msg = ''
        args = self.runtimeargs
        try:
            useImport = self.taskKwargs['import']
        except KeyError:
            useImport = False
        fn = translatepath(self.taskKwargs['pythonfile'])
        try:
            if len(self.runtimeargs) > 0:
                if useImport is False:
                    args = ' %s' % ' '.join(args)
                    result = xbmc.executebuiltin('XBMC.RunScript(%s, %s)' % (fn, args))
                else:
                    directory, module_name = os.path.split(fn)
                    module_name = os.path.splitext(module_name)[0]

                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name)
                        result = module.run(args)
                    finally:
                        sys.path[:] = path
            else:
                if useImport is False:
                    result = xbmc.executebuiltin('XBMC.RunScript(%s)' % fn)
                else:
                    directory, module_name = os.path.split(fn)
                    module_name = os.path.splitext(module_name)[0]

                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name)
                        result = module.run(args)
                    finally:
                        sys.path[:] = path
            if result is not None:
                msg = result
                if result != '':
                    err = True
        except Exception:
            e = sys.exc_info()[0]
            err = True
            if hasattr(e, 'message'):
                msg = str(e.message)
            msg = msg + '\n' + traceback.format_exc()

        self.threadReturn(err, msg)
 def run(self):
     if self.taskKwargs['notify'] is True:
         notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
     err = False
     msg = ''
     if isinstance(self.runtimeargs, list):
         if len(self.runtimeargs) > 0:
             self.runtimeargs = ''.join(self.runtimeargs)
         else:
             self.runtimeargs = ''
     try:
         if self.taskKwargs['user'] != '' and self.taskKwargs['pass'] != '':
             u = requests.get(self.taskKwargs['http']+self.runtimeargs, auth=(self.taskKwargs['user'], self.taskKwargs['pass']), timeout=20)
         else:
             u = requests.get(self.taskKwargs['http']+self.runtimeargs, timeout=20)
         try:
             result = u.text
         except Exception as e:
             err = True
             result = ''
             msg = _('Error on url read')
             if hasattr(e, 'message'):
                 msg = msg + '\n' + (str(e.message))
         msg = str(result)
     except requests.ConnectionError:
         err = True
         msg = _('Requests Connection Error')
     except requests.HTTPError:
         err = True
         msg = _('Requests HTTPError')
     except requests.URLRequired:
         err = True
         msg = _('Requests URLRequired Error')
     except requests.Timeout:
         err = True
         msg = _('Requests Timeout Error')
     except requests.RequestException:
         err = True
         msg = _('Generic Requests Error')
     except urllib2.HTTPError, e:
         err = True
         msg = _('HTTPError = ') + str(e.code)
Пример #10
0
    def run(self):
        """
        The following templated code is recommended. As above, self.taskKwargs contains your user input variables.
        There are a few other things added to taskKwargs (such as 'notify' seen below). If you have access to a debugger,
        stop the code here and look at that variable. Or try logging it as a string, if interested.
        self.runtimeargs contains the variable substituted event string.
        Information is passed out via the err and msg variables.

        ** If you generate any log messages here, surround them with the _(  , update=True) localization function.
        This will cause the po file to be updated with your strings.
        See below. During direct testing from the settings page, these log messages will be displayed on the screen
        """
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        err = False  # Change this to True if an error is encountered
        msg = ''  # Accumulate error or non-error information that needs to be returned in this string
        args = self.runtimeargs  # This contains a list derived from the variable subsituted event string
        # This list format is needed for using python's subprocess and Popen calls so that's why it is formatted
        # in this fashion.
        # If you need the args in a different format consider rejoining it into a string such as ' '.join(args) or
        # ', '.join(args). If you need something very different, you will need to override self.processUserargs()
        # See taskABC for the default processing and taskHttp for an example of overriding.
        assert isinstance(args, list)
        try:
            pass
            # Put your task implementation code here. Consider an inner try/except block accumulating specific error info
            # by setting err=True and appending to the message.
        except Exception:
            # Non-specific error catching and processing.
            e = sys.exc_info()[0]
            err = True
            if hasattr(e, 'message'):
                msg = str(e.message)
            msg = msg + '\n' + traceback.format_exc()
        # The following needs to be the last call. Since this code is running in its own thread, to pass information
        # backout, the following is formatted and placed in an output Queue where the parent thread is waiting.
        # If you do not pass anything out, a memory leak will accumulate with 'TaskManagers' accumulating over time.
        self.threadReturn(err, msg)
 def run(self):
     if self.taskKwargs['notify'] is True:
         notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
     err = False
     msg = ''
     args = ' %s' % ' '.join(self.runtimeargs)
     try:
         if len(self.runtimeargs) > 0:
             result = xbmc.executebuiltin('%s, %s' % (self.taskKwargs['builtin'], args))
         else:
             result = xbmc.executebuiltin('%s' % self.taskKwargs['builtin'])
         if result is not None:
             msg = result
             if result != '':
                 err = True
     except Exception:
         e = sys.exc_info()[0]
         err = True
         if hasattr(e, 'message'):
             msg = str(e.message)
         msg = msg + '\n' + traceback.format_exc()
     self.threadReturn(err, msg)
    def run(self):
        """
        The following templated code is recommended. As above, self.taskKwargs contains your user input variables.
        There are a few other things added to taskKwargs (such as 'notify' seen below). If you have access to a debugger,
        stop the code here and look at that variable. Or try logging it as a string, if interested.
        self.runtimeargs contains the variable substituted event string.
        Information is passed out via the err and msg variables.

        ** If you generate any log messages here, surround them with the _(  , update=True) localization function.
        This will cause the po file to be updated with your strings.
        See below. During direct testing from the settings page, these log messages will be displayed on the screen
        """
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        err = False  # Change this to True if an error is encountered
        msg = '' # Accumulate error or non-error information that needs to be returned in this string
        args = self.runtimeargs  # This contains a list derived from the variable subsituted event string
            # This list format is needed for using python's subprocess and Popen calls so that's why it is formatted
            # in this fashion.
            # If you need the args in a different format consider rejoining it into a string such as ' '.join(args) or
            # ', '.join(args). If you need something very different, you will need to override self.processUserargs()
            # See taskABC for the default processing and taskHttp for an example of overriding.
        assert isinstance(args, list)
        try:
            pass
            # Put your task implementation code here. Consider an inner try/except block accumulating specific error info
            # by setting err=True and appending to the message.
        except Exception:
            # Non-specific error catching and processing.
            e = sys.exc_info()[0]
            err = True
            if hasattr(e, 'message'):
                msg = str(e.message)
            msg = msg + '\n' + traceback.format_exc()
        # The following needs to be the last call. Since this code is running in its own thread, to pass information
        # backout, the following is formatted and placed in an output Queue where the parent thread is waiting.
        # If you do not pass anything out, a memory leak will accumulate with 'TaskManagers' accumulating over time.
        self.threadReturn(err, msg)
Пример #13
0
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        err = False
        msg = ''
        args = ' %s' % ' '.join(self.runtimeargs)
        # noinspection PyBroadException,PyBroadException,PyBroadException
        try:
            if len(self.runtimeargs) > 0:
                result = xbmc.executebuiltin(
                    '%s, %s' % (self.taskKwargs['builtin'], args))
            else:
                result = xbmc.executebuiltin('%s' % self.taskKwargs['builtin'])
            if result is not None:
                msg = result
                if result != '':
                    err = True
        except Exception as e:
            err = True
            msg = str(e)

        self.threadReturn(err, msg)
    def run(self):
        msg = ''
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        try:
            needs_shell = self.taskKwargs['use_shell']
        except KeyError:
            needs_shell = False
        try:
            wait = self.taskKwargs['waitForCompletion']
        except KeyError:
            wait = True
        tmpl = process_cmdline(self.taskKwargs['scriptfile'])
        filefound = False
        basedir = None
        sysexecutable = None
        for i, tmp in enumerate(tmpl):
            tmp = xbmc.translatePath(tmp)
            if os.path.exists(tmp) and filefound is False:
                basedir, fn = os.path.split(tmp)
                basedir = os.path.realpath(basedir)
                tmpl[i] = fn
                filefound = True
                if i == 0:
                    if os.path.splitext(fn)[1] == u'.sh':
                        if isAndroid:
                            sysexecutable = '/system/bin/sh'
                        elif not sysplat.startswith('win'):
                            sysexecutable = '/bin/bash'
            else:
                tmpl[i] = tmp
        if sysexecutable == '/system/bin/sh':
            tmpl.insert(0, 'sh')
        elif sysexecutable == '/bin/bash':
            tmpl.insert(0, 'bash')

        cwd = os.getcwd()
        args = tmpl + self.runtimeargs
        if needs_shell:
            args = ' '.join(args)
        err = False
        msg += 'taskScript ARGS = %s\n    SYSEXEC = %s\n BASEDIR = %s\n' % (args, sysexecutable, basedir)
        sys.exc_clear()
        try:
            if basedir is not None:
                os.chdir(basedir)
            if sysexecutable is not None:
                if isAndroid or sysplat.startswith('darwin'):
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT, executable=sysexecutable)
                else:
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT, executable=sysexecutable, cwd=basedir)
            else:
                if isAndroid or sysplat.startswith('darwin'):
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT)
                else:
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT, cwd=basedir)
            if wait:
                stdoutdata, stderrdata = p.communicate()
                if stdoutdata is not None:
                    stdoutdata = str(stdoutdata).strip()
                    if stdoutdata != '':
                        msg += _('Process returned data: [%s]\n') % stdoutdata
                    else:
                        msg += _('Process returned no data\n')
                else:
                    msg += _('Process returned no data\n')
                if stderrdata is not None:
                    stderrdata = str(stderrdata).strip()
                    if stderrdata != '':
                        msg += _('Process returned error: %s') % stdoutdata
        except ValueError, e:
            err = True
            msg = str(e)
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        try:
            needs_shell = self.taskKwargs['use_shell']
        except KeyError:
            needs_shell = False
        try:
            wait = self.taskKwargs['waitForCompletion']
        except KeyError:
            wait = True
        tmpl = shlex.split(self.taskKwargs['scriptfile'])
        filefound = False
        basedir = None
        sysexecutable = None
        for i, tmp in enumerate(tmpl):
            tmp = xbmc.translatePath(tmp).decode('utf-8')
            tmp = os.path.expanduser(tmp)
            tmp = os.path.expandvars(tmp)
            if os.path.exists(tmp) and filefound is False:
                basedir, fn = os.path.split(tmp)
                tmpl[i] = fn
                filefound = True
                if i == 0:
                    if os.path.splitext(fn)[1] == u'.sh':
                        if isAndroid:
                            sysexecutable = '/system/bin/sh'
                        elif not sysplat.startswith('win'):
                            sysexecutable = '/bin/bash'
            else:
                tmpl[i] = tmp
        if sysexecutable == '/system/bin/sh':
            tmpl.insert(0, 'sh')
        elif sysexecutable == '/bin/bash':
            tmpl.insert(0, 'bash')

        cwd = os.getcwd()
        args = tmpl + self.runtimeargs
        if needs_shell:
            args = ' '.join(args)
        err = False
        msg = ''
        sys.exc_clear()
        try:
            if basedir is not None:
                os.chdir(basedir)
            if sysexecutable is not None:
                p = subprocess.Popen(args,
                                     stdout=subprocess.PIPE,
                                     shell=needs_shell,
                                     stderr=subprocess.STDOUT,
                                     executable=sysexecutable,
                                     cwd=basedir)
            else:
                p = subprocess.Popen(args,
                                     stdout=subprocess.PIPE,
                                     shell=needs_shell,
                                     stderr=subprocess.STDOUT)
            if wait:
                stdoutdata, stderrdata = p.communicate()
                if stdoutdata is not None:
                    stdoutdata = str(stdoutdata).strip()
                    if stdoutdata != '':
                        msg = _('Process returned data: %s\n') % stdoutdata
                    else:
                        msg = _('Process returned no data\n')
                else:
                    msg = _('Process returned no data\n')
                if stderrdata is not None:
                    stderrdata = str(stderrdata).strip()
                    if stderrdata != '':
                        msg += _('Process returned error: %s') % stdoutdata
        except ValueError, e:
            err = True
            msg = str(e)
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        err = False
        msg = ''
        args = self.runtimeargs
        try:
            useImport = self.taskKwargs['import']
        except KeyError:
            useImport = False
        fn = translatepath(self.taskKwargs['pythonfile'])
        fse = sys.getfilesystemencoding()
        if fse is None:
            fse = 'utf-8'
        if sys.platform.lower().startswith('win'):
            if fn.encode('utf-8') != fn.encode(fse):
                fn = fsencode(fn)
        else:
            fn = fn.encode(fse)
        try:
            if len(self.runtimeargs) > 0:
                if useImport is False:
                    args = u' %s' % ' '.join(args)
                    try:
                        args = args.encode(fse)
                    except UnicodeEncodeError:
                        msg += 'Unicode Encode Error for "%s" Encoder: %s' % (args, fse)
                    result = xbmc.executebuiltin('XBMC.RunScript(%s, %s)' % (fn, args))
                else:
                    directory, module_name = os.path.split(self.taskKwargs['pythonfile'])
                    module_name = os.path.splitext(module_name)[0]
                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name.encode('utf-8'))
                        result = module.run(args)
                    finally:
                        sys.path[:] = path
            else:
                if useImport is False:
                    result = xbmc.executebuiltin(u'XBMC.RunScript(%s)' % fn)
                else:

                    directory, module_name = os.path.split(fn)
                    module_name = os.path.splitext(module_name)[0]

                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name.encode('utf-8'))
                        result = module.run(None)
                    finally:
                        sys.path[:] = path
            if result is not None:
                msg = result
                if result != '':
                    err = True
        except Exception:
            e = sys.exc_info()[0]
            err = True
            msg = u''
            if hasattr(e, 'message'):
                msg += unicode(e.message) + u'\n'
            msg +=  unicode(e) + u'\n'
            tb = traceback.format_exc()
            msg += tb.decode('utf-8')
        self.threadReturn(err, msg)
Пример #17
0
    def run(self):
        if self.taskKwargs['notify'] is True:
            notify(
                _('Task %s launching for event: %s') %
                (self.taskId, str(self.topic)))
        err = False
        msg = ''
        args = self.runtimeargs
        try:
            useImport = self.taskKwargs['import']
        except KeyError:
            useImport = False
        fn = translatepath(self.taskKwargs['pythonfile'])
        fse = sys.getfilesystemencoding()
        if fse is None:
            fse = 'utf-8'
        if sys.platform.lower().startswith('win'):
            if fn.encode('utf-8') != fn.encode(fse):
                fn = fsencode(fn)
        else:
            fn = fn.encode(fse)
        try:
            if len(self.runtimeargs) > 0:
                if useImport is False:
                    args = u' %s' % ' '.join(args)
                    try:
                        args = args.encode(fse)
                    except UnicodeEncodeError:
                        msg += 'Unicode Encode Error for "%s" Encoder: %s' % (
                            args, fse)
                    result = xbmc.executebuiltin('XBMC.RunScript(%s, %s)' %
                                                 (fn, args))
                else:
                    directory, module_name = os.path.split(
                        self.taskKwargs['pythonfile'])
                    module_name = os.path.splitext(module_name)[0]
                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name.encode('utf-8'))
                        result = module.run(args)
                    finally:
                        sys.path[:] = path
            else:
                if useImport is False:
                    result = xbmc.executebuiltin(u'XBMC.RunScript(%s)' % fn)
                else:

                    directory, module_name = os.path.split(fn)
                    module_name = os.path.splitext(module_name)[0]

                    path = list(sys.path)
                    sys.path.insert(0, directory)
                    try:
                        module = __import__(module_name.encode('utf-8'))
                        result = module.run(None)
                    finally:
                        sys.path[:] = path
            if result is not None:
                msg = result
                if result != '':
                    err = True
        except Exception:
            e = sys.exc_info()[0]
            err = True
            msg = u''
            if hasattr(e, 'message'):
                msg += unicode(e.message) + u'\n'
            msg += unicode(e) + u'\n'
            tb = traceback.format_exc()
            msg += tb.decode('utf-8')
        self.threadReturn(err, msg)
Пример #18
0
    def run(self):
        msg = u''
        if self.taskKwargs['notify'] is True:
            notify(_('Task %s launching for event: %s') % (self.taskId, str(self.topic)))
        try:
            needs_shell = self.taskKwargs['use_shell']
        except KeyError:
            needs_shell = False
        try:
            wait = self.taskKwargs['waitForCompletion']
        except KeyError:
            wait = True
        fse = sys.getfilesystemencoding()
        if fse is None:
            fse = 'utf-8'
        cmd = self.taskKwargs['scriptfile']
        if sysplat.startswith('win'):
            if cmd.encode('utf-8') != cmd.encode(fse):
                cmd = fsencode(self.taskKwargs['scriptfile'])
        tmpl = process_cmdline(cmd)
        filefound = False
        basedir = None
        sysexecutable = None
        for i, tmp in enumerate(tmpl):
            tmp = unicode(xbmc.translatePath(tmp), encoding='utf-8')
            if os.path.exists(tmp) and filefound is False:
                basedir, fn = os.path.split(tmp)
                basedir = os.path.realpath(basedir)
                tmpl[i] = fn
                filefound = True
                if i == 0:
                    if os.path.splitext(fn)[1] == u'.sh':
                        if isAndroid:
                            sysexecutable = u'/system/bin/sh'
                        elif not sysplat.startswith('win'):
                            sysexecutable = u'/bin/bash'
            else:
                tmpl[i] = tmp
        if sysexecutable == u'/system/bin/sh':
            tmpl.insert(0, u'sh')
        elif sysexecutable == u'/bin/bash':
            tmpl.insert(0, u'bash')

        cwd = os.getcwd()
        argsu = tmpl + self.runtimeargs

        args = []
        for arg in argsu:
            try:
                args.append(arg.encode(fse))
            except UnicodeEncodeError:
                msg += u'Unicode Encode Error for: "%s" Encoder: %s' % (arg, fse)
        if needs_shell:
            args = ' '.join(args)
        err = False
        msg += u'taskScript ARGS = %s\n    SYSEXEC = %s\n BASEDIR = %s\n' % (args, sysexecutable, basedir)
        sys.exc_clear()

        try:
            if basedir is not None:
                os.chdir(basedir)
            if sysexecutable is not None:
                if isAndroid or sysplat.startswith('darwin'):
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT, executable=sysexecutable)
                else:
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT, executable=sysexecutable, cwd=basedir)
            else:
                if isAndroid or sysplat.startswith('darwin'):
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT)
                else:
                    p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=needs_shell, stderr=subprocess.STDOUT, cwd=basedir)
            if wait:
                stdoutdata, stderrdata = p.communicate()
                if stdoutdata is not None:
                    stdoutdata = stdoutdata.decode(fse, 'ignore').strip()
                    if stdoutdata != '':
                        msg += _(u'Process returned data: [%s]\n') % stdoutdata
                    else:
                        msg += _(u'Process returned no data\n')
                else:
                    msg += _(u'Process returned no data\n')
                if stderrdata is not None:
                    stderrdata = stderrdata.decode(fse, 'ignore').strip()
                    if stderrdata != '':
                        msg += _(u'Process returned error: %s') % stderrdata
        except ValueError, e:
            err = True
            msg = unicode(e)