Example #1
0
def build(path):
    for name in os.listdir(path):
        source = os.path.join(path, name)
        target = None
        if source.endswith(".ui"):
            target = os.path.join(path,
                                  "ui_" + name.replace(".ui", ".py"))
            command = PYUIC4
        elif source.endswith(".qrc"):
            target = os.path.join(path,
                                  name.replace(".qrc", "") + "_rc.py")
            command = PYRCC4
        process = QProcess()
        if target is not None:
            if not os.access(target, os.F_OK) or (
               os.stat(source)[stat.ST_MTIME] > \
               os.stat(target)[stat.ST_MTIME]):
                if command == PYUIC4 and Execute:
                    args  = ["-x", "-o", target, source]
                else:
                    args  = ["-o", target, source]
                if Debug:
                    print "# %s -o %s %s" % (command, target, source)
                else:
                    process.start(command, args)
                    if not process.waitForFinished(2 * 60 * 1000):
                        report_failure(command, args, process)
                    else:
                        print source, "->", target
            elif Verbose:
                print source, "is up-to-date"
Example #2
0
 def __init__(self, ID=None):
     self.Test = QProcess()
     self.ID = ID
     #a and b to test if i get a output or command error
     self.a = True
     self.Settings = QtCore.QSettings('Tyrant.cfg',
                                      QtCore.QSettings.IniFormat)
Example #3
0
def main():
    app = QApplication(sys.argv)
    window = QSimpleShellWidget()
    proc = QProcess()
    window.setProcess(proc)
    proc.start('sh -c "while true; do echo foo; sleep 1; done"')
    window.show()
    app.exec_()
Example #4
0
 def testNoArgs(self):
     '''Connecting a lambda to a signal without arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('started()'),
                     lambda: setattr(dummy, 'called', True))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assert_(dummy.called)
Example #5
0
    def __init__(self):
        super(TasksPool, self).__init__()
        self.tasks_pool = []
        self.process = QProcess()

        self.startNextTaskSignal.connect(self.execute_task)
        self.allTasksCompleteSignal.connect(self.tasks_complete)

        self.source = ''
Example #6
0
 def __init__(self, finishedHook=None, stdoutHook=None, stderrHook=None):
     self.process = QProcess()
     self.finishedHook = finishedHook
     self.stdoutHook = stdoutHook
     self.stderrHook = stderrHook
     self.process.finished.connect(self.finished)
     self.process.readyReadStandardOutput.connect(self.readStdout)
     self.process.readyReadStandardError.connect(self.readStderr)
     self.print_next_error_lines = 0
     self.print_next_error_file = False
Example #7
0
    def run(self):

        self.logger.debug("patcher started")
        for patch in self.patches:
            mod = patch["mod"]
            fromFile = patch["patchfile"]
            toFile = patch["tofilename"]
            frommd5 = patch["md5"]
            tomd5 = patch["tomd5"]

            curPatchGen = "%s-%s.xdelta" % (fromFile, toFile)

            self.logger.debug(curPatchGen)

            self.logger.debug("opening database")
            self.db = QtSql.QSqlDatabase.cloneDatabase(self.parentDb,
                                                       curPatchGen)
            source = os.path.join(
                config['global']['content_path'] + r"updaterNew/", mod,
                fromFile)
            target = os.path.join(
                config['global']['content_path'] + r"updaterNew/", mod, toFile)

            self.logger.debug(source)
            self.logger.debug(target)

            patchdest = os.path.join(
                config['global']['content_path'] + r"xdelta/", curPatchGen)
            self.logger.debug(patchdest)

            if os.path.exists(source) and os.path.exists(target):

                executable = "python"
                arguments = [
                    config['global']['install_path'] + "patcher.py", source,
                    target, patchdest
                ]

                self.logger.debug(arguments)
                process = QProcess()

                process.start(executable, arguments)

                if not process.waitForFinished(28800000):
                    return

                self.db.open()
                query = QSqlQuery(self.db)
                queryStr = (
                    "INSERT INTO patchs_table (fromMd5, toMd5, patchFile) VALUES ('%s','%s','%s')"
                ) % (frommd5, tomd5, curPatchGen)
                query.exec_(queryStr)
                #
                self.db.close()
Example #8
0
def detach(args, path=''):
    """
  @param  args  [unicode]
  @param* path  unicode  working directory
  @return  bool
  """
    from PySide.QtCore import QProcess
    dprint("path: %s" % (path or '(empty)'))
    dprint(args)
    if path:
        return QProcess.startDetached(args[0], args[1:], path)
    else:
        return QProcess.startDetached(args[0], args[1:])
Example #9
0
    def start(self, messageElement):

        Stream.clear_streams()

        process = QProcess()

        self.process = process
        self.messageElement = messageElement

        process.setProcessChannelMode(QProcess.MergedChannels)
        process.start("livestreamer", self.arguments)
        process.readyReadStandardOutput.connect(self.show_messages)

        Stream.ALL_STREAMS.append(self)
Example #10
0
 def process(self, command):
     #       print "process"
     content = "content"
     process = QProcess()
     process.start(command)
     process.closeWriteChannel()
     process.waitForFinished()
     #       process.closeWriteChannel()
     content = process.readAllStandardOutput()
     print "Content: " + content
     return unicode(content)
Example #11
0
    def run(self):
        if self.ui.cb_batch.isChecked():
            self.last_log_file = None
        else:
            f_next, _ = os.path.splitext(str(self.ui.edit_file.text()))        
            f_params = f_next + '.params'
            if not os.path.exists(f_params):
                self.create_params_file(f_params)
                self.ui.btn_param.setEnabled(True)
                return
            self.last_log_file = f_next + '.log'
        
        if self.ui.tabWidget.currentIndex() == 0:
            args = self.command_line_args()
        elif self.ui.tabWidget.currentIndex() == 1:
            args = self.gui_command_line_args()
        
        self.update_result_tab()

        # # Start process
        self.ui.edit_stdout.clear()
        format = self.ui.edit_stdout.currentCharFormat()
        format.setFontWeight(QFont.Normal)
        format.setForeground(QtCore.Qt.blue)
        self.ui.edit_stdout.setCurrentCharFormat(format)
        time_str = datetime.datetime.now().ctime()
        start_msg = '''\
                       Starting spyking circus at {time_str}.

                       Command line call:
                       {call}
                    '''.format(time_str=time_str, call=' '.join(args))
        self.ui.edit_stdout.appendPlainText(textwrap.dedent(start_msg))
        format.setForeground(QtCore.Qt.black)
        self.ui.edit_stdout.setCurrentCharFormat(format)
        self.ui.edit_stdout.appendPlainText('\n')

        self.process = QProcess(self)
        self.connect(self.process, SIGNAL('readyReadStandardOutput()'), self.append_output)
        self.connect(self.process, SIGNAL('readyReadStandardError()'),
                     self.append_error)
        self.connect(self.process, SIGNAL('started()'),
                     self.process_started)
        self.connect(self.process, SIGNAL('finished(int)'),
                     self.process_finished)
        self.connect(self.process, SIGNAL('error()'),
                     self.process_errored)
        self._interrupted = False
        self.process.start(args[0], args[1:])
Example #12
0
 def __execute_task(self, task):
     """
     :param task: Is a string used to start a process
     """
     self.process = QProcess(self)
     self.process.finished.connect(
         lambda *x: logger.debug(task + ' reports complete'))
     self.process.finished.connect(lambda *x: self.return_signal.emit(
         'â–º' + task + 'â—„reports complete'))
     self.process.finished.connect(self.task_done)
     # self.process.readyRead.connect(lambda *x: print(str(self.process.readAll())))
     self.process.readyRead.connect(
         lambda *x: self.return_signal.emit(str(self.process.readAll())))
     self.process.setProcessChannelMode(QProcess.MergedChannels)
     self.process.start(task)
Example #13
0
 def execute_task(self):
     print('Start next?')
     if self.process.isOpen():
         self.process.waitForFinished()
     if not self.tasks_pool:
         self.allTasksCompleteSignal.emit()
         return
     self.process = QProcess()
     self.process.finished.connect(
         lambda *x: QTimer.singleShot(1000, self.startNextTaskSignal.emit))
     self.process.setProcessChannelMode(QProcess.MergedChannels)
     self.process.readyRead.connect(self.process_output)
     next_task = self.tasks_pool.pop(0)
     print('NEXT TASK', next_task)
     self.process.start(next_task)
Example #14
0
class TasksPool(QObject):
    """
    This class allows you to add_task() for execution queue. Launch_list() starts the queue.
    """
    task_done = Signal()
    return_signal = Signal(str)

    def __init__(self):

        super(TasksPool, self).__init__()
        self.tasks_pool = []
        self.process = None
        if not QApplication.instance():
            self.qapp = QApplication([])

    def add_task(self, command):
        """
        :type command: str
        :param command: A console command with arguments
        Adds a task to the pool for later execution
        """
        self.tasks_pool.append(command)

    def __execute_task(self, task):
        """
        :param task: Is a string used to start a process
        """
        self.process = QProcess(self)
        self.process.finished.connect(
            lambda *x: logger.debug(task + ' reports complete'))
        self.process.finished.connect(lambda *x: self.return_signal.emit(
            'â–º' + task + 'â—„reports complete'))
        self.process.finished.connect(self.task_done)
        # self.process.readyRead.connect(lambda *x: print(str(self.process.readAll())))
        self.process.readyRead.connect(
            lambda *x: self.return_signal.emit(str(self.process.readAll())))
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        self.process.start(task)

    def launch_list(self):
        """
        Starts the execution of the queue in consecutive order, waiting for previous process to finish
        """
        for task in self.tasks_pool:
            loop = QEventLoop()
            self.task_done.connect(loop.quit)
            self.__execute_task(task)
            loop.exec_()
Example #15
0
    def init_broker(self):
        print "[*] init_broker"
        modname = self.input.text().encode('ascii', 'replace')
        cmdline = u"\"%s\" -u \"%s\" --idb \"%s\"" % (
                  os.path.join(PYTHON_PATH, PYTHON_BIN),
                  BROKER_PATH, modname)
        print "[*] init broker,", cmdline

        self.broker = Broker(self.parser)
        env = QProcess.systemEnvironment()
        env.append("IDB_PATH=%s" % IDB_PATH)
        env.append("PYTHON_PATH=%s" % os.path.realpath(PYTHON_PATH))
        env.append("PYTHON_BIN=%s" % PYTHON_BIN)

        try:
            self.broker.connect(self.broker, QtCore.SIGNAL("started()"),  self.cb_broker_started)
            self.broker.connect(self.broker, QtCore.SIGNAL("finished(int)"),  self.cb_broker_finished)
            self.broker.setEnvironment(env)
            self.broker.start(cmdline)
        except Exception as e:
            print "[-] failed to start broker: %s\n%s" % (str(e), traceback.format_exc())
            return

        self.init_hotkeys()
        self.broker.worker.name = modname
Example #16
0
 def __init__(self, ID=None):
     self.Test = QProcess()
     self.ID = ID
     #a and b to test if i get a output or command error
     self.a = True
     self.Settings = QtCore.QSettings('Tyrant.cfg',
                                                 QtCore.QSettings.IniFormat)
Example #17
0
    def init_broker(self):
        print "[*] init_broker"
        modname = self.input.text().encode('ascii', 'replace')
        cmdline = u"\"%s\" -u \"%s\" --idb \"%s\"" % (
                  os.path.join(PYTHON_PATH, PYTHON_BIN),
                  BROKER_PATH, modname)
        print "[*] init broker,", cmdline

        self.broker = Broker(self.parser)
        env = QProcess.systemEnvironment()
        env.append("IDB_PATH=%s" % IDB_PATH)
        env.append("PYTHON_PATH=%s" % os.path.realpath(PYTHON_PATH))
        env.append("PYTHON_BIN=%s" % PYTHON_BIN)

        try:
            self.broker.connect(self.broker, QtCore.SIGNAL("started()"),  self.cb_broker_started)
            self.broker.connect(self.broker, QtCore.SIGNAL("finished(int)"),  self.cb_broker_finished)
            self.broker.setEnvironment(env)
            self.broker.start(cmdline)
        except Exception as e:
            print "[-] failed to start broker: %s\n%s" % (str(e), traceback.format_exc())
            return

        self.init_hotkeys()
        self.broker.worker.name = modname
Example #18
0
 def get_output(cmd):
     if isinstance(cmd, list):
         cmd = ' '.join(cmd)
     process = QProcess()
     process.start(cmd)
     process.waitForFinished()
     return str(process.readAll())
Example #19
0
def translate(path):
    files = []
    tsfiles = []
    for name in os.listdir(path):
        if name.endswith((".py", ".pyw")):
            files.append(os.path.join(path, name))
        elif name.endswith(".ts"):
            tsfiles.append(os.path.join(path, name))
    if not tsfiles:
        return
    verbose = "-verbose" if Verbose else ""
    silent = "-silent" if not Verbose else ""
    process = QProcess()
    for ts in tsfiles:
        qm = ts[:-3] + ".qm"
        command1 = PYLUPDATE4
        args1 = [verbose] + files + ["-ts", ts]
        command2 = LRELEASE
        args2 = [silent, ts, "-qm", qm]
        if Debug:
            print "updated", ts
            print "generated", qm
        else:
            process.start(command1, args1)
            if not process.waitForFinished(2 * 60 * 1000):
                report_failure(command1, args1, process)
            process.start(command2, args2)
            if not process.waitForFinished(2 * 60 * 1000):
                report_failure(command2, args2, process)
Example #20
0
    def run(self) :
 
        self.logger.debug("patcher started")
        for patch in self.patches:
            mod = patch["mod"]
            fromFile = patch["patchfile"]
            toFile = patch["tofilename"]
            frommd5 = patch["md5"]
            tomd5 = patch["tomd5"]

            curPatchGen = "%s-%s.xdelta" % (fromFile, toFile)

            self.logger.debug(curPatchGen)

            self.logger.debug("opening database")
            self.db = QtSql.QSqlDatabase.cloneDatabase(self.parentDb, curPatchGen)
            source = os.path.join(config['global']['content_path'] + r"updaterNew/", mod, fromFile)
            target = os.path.join(config['global']['content_path'] + r"updaterNew/", mod, toFile)
        
            self.logger.debug(source)
            self.logger.debug(target)

            patchdest = os.path.join(config['global']['content_path'] + r"xdelta/", curPatchGen)
            self.logger.debug(patchdest)            
            
            if os.path.exists(source) and os.path.exists(target) : 
                        
                executable = "python"
                arguments = [config['global']['install_path'] + "patcher.py", source, target, patchdest]
                
                self.logger.debug(arguments)
                process = QProcess()
                
                
                process.start(executable, arguments)

                if not process.waitForFinished(28800000) :
                    return
                
                self.db.open()
                query = QSqlQuery(self.db)
                queryStr = ("INSERT INTO patchs_table (fromMd5, toMd5, patchFile) VALUES ('%s','%s','%s')") % (frommd5, tomd5, curPatchGen)
                query.exec_(queryStr)
    #        
                self.db.close()
Example #21
0
    def testWithoutArgs(self):
        """Connect QProcess.started() to QTimeLine.togglePaused()"""
        process = QProcess()
        timeline = QTimeLine()

        QObject.connect(process, SIGNAL("finished(int, QProcess::ExitStatus)"), timeline, SLOT("toggleDirection()"))

        orig_dir = timeline.direction()

        process.start(sys.executable, ["-c", '"print 42"'])
        process.waitForFinished()

        new_dir = timeline.direction()

        if orig_dir == QTimeLine.Forward:
            self.assertEqual(new_dir, QTimeLine.Backward)
        else:
            self.assertEqual(new_dir, QTimeLine.Forward)
Example #22
0
	def is_online( self, tableWidgetItem ):

		Stream.clear_streams()
		process = QProcess()
		self.process = process
		self.table_widget_item = tableWidgetItem

		arguments = [ '--json' ] + self.arguments

		process.setProcessChannelMode( QProcess.MergedChannels )
		process.start( 'livestreamer', arguments )
		process.readyReadStandardOutput.connect( self.is_online_callback )

		itemWidget = self.table_widget_item
		tableWidget = itemWidget.tableWidget()
		tableWidget.setCellWidget( itemWidget.row(), 0, MovieWidget( fullpath( 'icons/loading_16.gif' ), tableWidget) )

		Stream.ALL_STREAMS.append( self )
Example #23
0
    def process(self,command):
#       print "process"
        content = "content"
        process = QProcess()
        process.start(command)
        process.closeWriteChannel()
        process.waitForFinished()
#       process.closeWriteChannel()
        content = process.readAllStandardOutput()
        print "Content: " + content
        return unicode(content);
    def testQProcessFinished(self):
        '''Multiple connections to QProcess.finished(int)'''
        sender = QProcess()
        receivers = [BasicPySlotCase() for x in range(10)]

        def start_proc(*args):
            sender.start(sys.executable, ['-c', '""'])
            sender.waitForFinished()

        self.run_many(sender, 'finished(int)', start_proc, receivers, (0, ))
Example #25
0
 def __init__(self, media, parent):
     super(WebMediaView, self).__init__(media, parent)
     self.widget = QWidget(parent)
     self.process = QProcess(self.widget)
     self.process.setObjectName('%s-process' % self.objectName())
     self.std_out = []
     self.errors = []
     self.stopping = False
     self.mute = False
     self.widget.setGeometry(media['geometry'])
     self.connect(self.process, SIGNAL('error()'), self.process_error)
     self.connect(self.process, SIGNAL('finished()'), self.process_finished)
     self.connect(self.process, SIGNAL('started()'), self.process_started)
     self.set_default_widget_prop()
     self.stop_timer = QTimer(self)
     self.stop_timer.setSingleShot(True)
     self.stop_timer.setInterval(1000)
     self.stop_timer.timeout.connect(self.process_timeout)
     self.rect = self.widget.geometry()
Example #26
0
	def start( self, messageElement, tableWidgetItem ):

		Stream.clear_streams()

		process = QProcess()
		self.process = process
		self.messageElement = messageElement

		row = tableWidgetItem.row()
		tableWidget = tableWidgetItem.tableWidget()
		tableWidget.setCellWidget( tableWidgetItem.row(), 0, ImageWidget( fullpath( 'icons/play_16.png' ), tableWidget) )
		tableWidgetItem = tableWidget.item( row, 0 )

		process.setProcessChannelMode( QProcess.MergedChannels )
		process.start( 'livestreamer', self.arguments )
		process.readyReadStandardOutput.connect( self.show_messages )
		process.finished.connect( lambda: self.is_online( tableWidgetItem ) )

		Stream.ALL_STREAMS.append( self )
Example #27
0
 def testWithArgs(self):
     '''Connecting a lambda to a signal with arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('finished(int)'),
                     lambda x: setattr(dummy, 'called', x))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assertEqual(dummy.called, proc.exitCode())
 def get_output(cmd):
     if isinstance(cmd, list):
         cmd = ' '.join(cmd)
     process = QProcess()
     process.start(cmd)
     process.waitForFinished()
     return str(process.readAll())
Example #29
0
    def is_online(self, tableWidgetItem):

        Stream.clear_streams()

        process = QProcess()

        self.process = process
        self.table_widget_item = tableWidgetItem

        arguments = ["--json"] + self.arguments

        process.setProcessChannelMode(QProcess.MergedChannels)
        process.start("livestreamer", arguments)
        process.readyReadStandardOutput.connect(self.is_online_callback)

        brush = QBrush(Qt.SolidPattern)
        color = QColor(255, 255, 255)  # white
        brush.setColor(color)
        tableWidgetItem.setBackground(brush)
        tableWidgetItem.setText("Checking..")

        Stream.ALL_STREAMS.append(self)
Example #30
0
def neko(neko_id='neko:v2Yr'):
    _, id = neko_id.split(":")

    url = BASE_URL.format(id)
    if not DEBUG:
        res = requests.get(url).json()
    else:
        res = _response
    mega_url = res.get("url","")
    version = res.get("version", -1)
    if VER != version:
        print cat
        print "Hay una version nueva!!! descargala"
        raw_input("adios ...")
        return
    print cat
    if _platform == "linux" or _platform == "linux2":
        mega_path = "megadl"
        mpv_path = "mpv"
    elif _platform == "darwin": # MAC OS X
        pass
    elif _platform == "win32": # Windows
        mega_path = os.path.join(BASE_DIR, 'mega', 'megadl.exe')
        mpv_path = os.path.join(BASE_DIR, "mpv","mpv.com")
    p1 = QProcess()
    p2 = QProcess()
    p1.setStandardOutputProcess(p2)
    p1.start('{}'.format(mega_path), ['{}'.format(mega_url),"--path","-"])
    p2.start('{}'.format(mpv_path), ["-" , '--no-terminal'])
    p2.waitForFinished(-1)

    #print p2.readAll()
#           "--path","-",)
    #cmd = ['"{}"'.format(mega_path), '"{}"'.format(mega_url),
#           "--path","-","|",
#           '"{}"'.format(mpv_path), "-" , '--no-terminal']
           #'--fullscreen']
    print "Cargando...."
Example #31
0
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self._widget = QWidget(parent)
        self._process = QProcess(self._widget)
        self._process.setObjectName('%s-process' % self.objectName())
        self._std_out = []
        self._errors = []
        self._stopping = False
        self._mute = False
        if 'mute' in self._options:
            self._mute = bool(int(self._options['mute']))

        self._widget.setGeometry(media['_geometry'])
        self.connect(self._process, SIGNAL("error()"), self._process_error)
        self.connect(self._process, SIGNAL("finished()"), self.stop)
        self.connect(self._process, SIGNAL("readyReadStandardOutput()"),
                     self.__grep_std_out)
        self.set_default_widget_prop()

        self._stop_timer = QTimer(self)
        self._stop_timer.setSingleShot(True)
        self._stop_timer.setInterval(1000)
        self._stop_timer.timeout.connect(self._force_stop)
Example #32
0
 def testNoArgs(self):
     '''Connecting a lambda to a signal without arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('started()'),
                     lambda: setattr(dummy, 'called', True))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assert_(dummy.called)
Example #33
0
 def testWithArgs(self):
     '''Connecting a lambda to a signal with arguments'''
     proc = QProcess()
     dummy = Dummy()
     QObject.connect(proc, SIGNAL('finished(int)'),
                     lambda x: setattr(dummy, 'called', x))
     proc.start(sys.executable, ['-c', '""'])
     proc.waitForFinished()
     self.assertEqual(dummy.called, proc.exitCode())
Example #34
0
def start_autostarts():

        global autostart_processlist, logger
        
        autostarts = {}
                
        sl = clixxIOProjectAutostarts()

        for sp in sl.keys():
            
            p = QProcess()
            p.setWorkingDirectory(sl[sp]["directory"])
            
            program = sl[sp]["command"]
            arguments = sl[sp]["arguments"].split(' ')

            logger.debug("Starting %s in %s with arguments %s" % (program,sl[sp]["directory"],arguments))

            # Start the process running
            autostart_processlist.append(p)
            autostart_processlist[len(autostart_processlist)-1].start(program, arguments)

        for p in range(0,len(autostart_processlist)-1):
            logger.debug("PID=%d" % autostart_processlist[p].pid())
Example #35
0
class TasksPool(QObject):
    startNextTaskSignal = Signal()
    allTasksCompleteSignal = Signal()

    def __init__(self):
        super(TasksPool, self).__init__()
        self.tasks_pool = []
        self.process = QProcess()

        self.startNextTaskSignal.connect(self.execute_task)
        self.allTasksCompleteSignal.connect(self.tasks_complete)

        self.source = ''

    def add_task(self, command):
        self.tasks_pool.append(command)
        self.startNextTaskSignal.emit()

    def execute_task(self):
        print('Start next?')
        if self.process.isOpen():
            self.process.waitForFinished()
        if not self.tasks_pool:
            self.allTasksCompleteSignal.emit()
            return
        self.process = QProcess()
        self.process.finished.connect(
            lambda *x: QTimer.singleShot(1000, self.startNextTaskSignal.emit))
        self.process.setProcessChannelMode(QProcess.MergedChannels)
        self.process.readyRead.connect(self.process_output)
        next_task = self.tasks_pool.pop(0)
        print('NEXT TASK', next_task)
        self.process.start(next_task)

    def process_output(self):
        output = self.process.readAll()
        output = str(output).strip()
        if output:
            print(output)

    def tasks_complete(self):
        print('ALL TASKS COMPLETE')
Example #36
0
    def start(self, messageElement):

        Stream.clear_streams()

        process = QProcess()

        self.process = process
        self.messageElement = messageElement

        process.setProcessChannelMode(QProcess.MergedChannels)
        process.start('livestreamer', self.arguments)
        process.readyReadStandardOutput.connect(self.show_messages)

        Stream.ALL_STREAMS.append(self)
Example #37
0
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self._widget = QWidget(parent)
        self._process = QProcess(self._widget)
        self._process.setObjectName('%s-process' % self.objectName())
        self._std_out = []
        self._errors = []
        self._stopping = False
        self._mute = False
        if 'mute' in self._options:
            self._mute = bool(int(self._options['mute']))

        self._widget.setGeometry(media['_geometry'])
        self.connect(self._process, SIGNAL("error()"), self._process_error)
        self.connect(self._process, SIGNAL("finished()"), self.stop)
        self.connect(self._process, SIGNAL("readyReadStandardOutput()"), self.__grep_std_out)
        self.set_default_widget_prop()

        self._stop_timer = QTimer(self)
        self._stop_timer.setSingleShot(True)
        self._stop_timer.setInterval(1000)
        self._stop_timer.timeout.connect(self._force_stop)
Example #38
0
    def is_online(self, tableWidgetItem):

        Stream.clear_streams()

        process = QProcess()

        self.process = process
        self.table_widget_item = tableWidgetItem

        arguments = ['--json'] + self.arguments

        process.setProcessChannelMode(QProcess.MergedChannels)
        process.start('livestreamer', arguments)
        process.readyReadStandardOutput.connect(self.is_online_callback)

        tableWidgetItem.setText('Checking..')

        Stream.ALL_STREAMS.append(self)
Example #39
0
    def testWithoutArgs(self):
        '''Connect QProcess.started() to QTimeLine.togglePaused()'''
        process = QProcess()
        timeline = QTimeLine()

        QObject.connect(process, SIGNAL('finished(int, QProcess::ExitStatus)'),
                        timeline, SLOT('toggleDirection()'))

        orig_dir = timeline.direction()

        process.start(sys.executable, ['-c', '"print 42"'])
        process.waitForFinished()

        new_dir = timeline.direction()

        if orig_dir == QTimeLine.Forward:
            self.assertEqual(new_dir, QTimeLine.Backward)
        else:
            self.assertEqual(new_dir, QTimeLine.Forward)
Example #40
0
def runtapinstall(args, errorok=False):
    EXE = '%s/%s' % (TAPDIR, TAPINSTALL)
#    args.insert(0, EXE)
#    cmd = ' '.join(args)
    process = QProcess()
    process.start(EXE, args)
    if not process.waitForFinished():
        print "tapinstall failed. waitForFinished()"
        sys.exit(1)
    output = process.readAll();
    rv = process.exitStatus()
    output=str(output).strip()
    if rv != 0 and not errorok:
        print """tapinstall failed.
command was: %s
output was: %s
returnvalue was: %d""" % (cmd, output, rv)
        sys.exit(1)
    else:
        return (rv, output)
Example #41
0
    def is_online(self, tableWidgetItem):

        Stream.clear_streams()

        process = QProcess()

        self.process = process
        self.table_widget_item = tableWidgetItem

        arguments = ['--json'] + self.arguments

        process.setProcessChannelMode(QProcess.MergedChannels)
        process.start('livestreamer', arguments)
        process.readyReadStandardOutput.connect(self.is_online_callback)

        brush = QBrush(Qt.SolidPattern)
        color = QColor(255, 255, 255)  #white
        brush.setColor(color)
        tableWidgetItem.setBackground(brush)
        tableWidgetItem.setText('Checking..')

        Stream.ALL_STREAMS.append(self)
Example #42
0
def parse_asn1(*files, **options):
    ''' Call the ASN.1 parser on a number of files, and return the module
        containing the AST
        This function uses QProcess to launch the ASN.1 compiler because
        the subprocess module from Python has issues on the Windows platform
    '''
    ast_version = options.get('ast_version', ASN1.UniqueEnumeratedNames)
    rename_policy = options.get('rename_policy', ASN1.NoRename)
    flags = options.get('flags', [ASN1.AstOnly])
    pprint = options.get('pretty_print', False)
    assert isinstance(ast_version, ASN1)
    assert isinstance(rename_policy, ASN1)
    assert isinstance(flags, list)
    path_to_asn1scc = spawn.find_executable('asn1.exe')

    if not path_to_asn1scc:
        raise TypeError('ASN.1 Compiler not found in path')
    if os.name == 'posix':
        path_to_mono = spawn.find_executable('mono')
        if not path_to_mono:
            raise TypeErorr('"mono" not found in path. Please install it.')
        binary = path_to_mono
        arg0 = path_to_asn1scc
    else:
        binary = path_to_asn1scc
        arg0 = ''
    asn1scc_root = os.path.abspath(os.path.dirname(path_to_asn1scc))
    # Create a temporary directory to store dataview.py and import it
    tempdir = tempfile.mkdtemp()
    sys.path.append(tempdir)
    if os.name == 'nt':
        # On windows, remove the drive letter, workaround to ASN1SCC bug
        tempdir = tempdir[2:]
        asn1scc_root = asn1scc_root[2:]
    filename = str(uuid.uuid4()).replace('-', '_')
    filepath = tempdir + os.sep + filename + '.py'

    stg = asn1scc_root + os.sep + 'python.stg'

    if pprint:
        # Generate an html file with pretty-printed ASN.1 types
        stg_qrc = QFile(':misc/pretty_print_asn1.stg')
        stg_qrc.open(1)
        content = stg_qrc.readAll()
        stgfile = tempdir + os.sep + 'pretty_print_asn1.stg'
        with open(stgfile, 'w') as tmpfile:
            tmpfile.write(content.data())
        out_html = tempdir + os.sep + 'dataview.html'
        html = ['-customIcdUper', stgfile + '::' + out_html]
    else:
        html = []
    args = [
        arg0, '-customStgAstVerion',
        str(ast_version.value), '-customStg', stg + '::' + filepath,
        '-renamePolicy',
        str(rename_policy.value)
    ] + html + list(*files)
    asn1scc = QProcess()
    LOG.debug(os.getcwd())
    LOG.debug(binary + ' ' + ' '.join(args))
    asn1scc.start(binary, args)

    _ = waitfor_qprocess(asn1scc, "ASN.1 Compiler")

    if filename in AST.viewkeys():
        # Re-import module if it was already loaded
        ast = AST[filename]
        reload(ast)
    else:
        ast = importlib.import_module(filename)
        AST[filename] = ast
    if pprint:
        # add the path to the optionally-gernated pretty-printed HTML file
        ast.html = out_html
    return ast
Example #43
0
def asn2dataModel(*files):
    ''' Call asn1DataModel, including the Makefile.python and return
    the imported module "name_of_dataview_asn.py"
    From this module it is possible to create native Asn1scc instances of
    ASN.1 data types, and to access to DV.py, which contains constants
    such as the _PRESENT fields for choice selectors '''
    assert len(files) > 0

    # 1) Create a temporary directory for the output
    tempdir = tempfile.mkdtemp()
    sys.path.insert(0, tempdir)
    # Use a unique name for the asn1 concatenated module
    concat_prefix = str(uuid.uuid4()).replace('-', '_')
    concat_path = os.path.join(tempdir, concat_prefix)

    # 2) Concat all input files to the output directory
    cat_bin = spawn.find_executable('cat')
    args = list(files)
    cat = QProcess()
    LOG.debug(os.getcwd())
    LOG.debug(cat_bin + ' ' + ' '.join(args))
    cat.start(cat_bin, args)
    merged = waitfor_qprocess(cat, 'Merge dataviews')
    with open(concat_path + '.asn', 'wt') as merged_file:
        merged_file.write(merged)

    # 3) Run asn2dataModel
    asn2dm_bin = spawn.find_executable('asn2dataModel')
    args = ['-toPython', '-o', tempdir, concat_path + '.asn']
    asn2dm = QProcess()
    LOG.debug(os.getcwd())
    LOG.debug(asn2dm_bin + ' ' + ' '.join(args))
    asn2dm.start(asn2dm_bin, args)
    waitfor_qprocess(asn2dm, 'DMT tool "asn2dataModel"')

    # 4) call make -f Makefile.python to build the .so
    make_bin = spawn.find_executable('make')
    args = ['-f', 'Makefile.python']
    make = QProcess()
    make.setWorkingDirectory(tempdir)
    LOG.debug(os.getcwd())
    LOG.debug(make_bin + ' ' + ' '.join(args))
    make.start(make_bin, args)
    waitfor_qprocess(make, 'make -f Makefile.python')

    if concat_prefix in ASN2DM.viewkeys():
        # Re-import module if it was already loaded
        asn1mod = ASN2DM[concat_prefix]
        reload(asn1mod)
        reload(asn1mod.DV)
        import Stubs
        reload(Stubs)
    else:
        asn1mod = importlib.import_module(concat_prefix + '_asn')
        # force reload of modules in case of multiple calls
        reload(asn1mod.DV)
        import Stubs
        reload(Stubs)
        ASN2DM[concat_prefix] = asn1mod
    sys.path.pop(0)
    return asn1mod
Example #44
0
class VideoMediaView(MediaView):
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self._widget = QWidget(parent)
        self._process = QProcess(self._widget)
        self._process.setObjectName('%s-process' % self.objectName())
        self._std_out = []
        self._errors = []
        self._stopping = False
        self._mute = False
        if 'mute' in self._options:
            self._mute = bool(int(self._options['mute']))

        self._widget.setGeometry(media['_geometry'])
        self.connect(self._process, SIGNAL("error()"), self._process_error)
        self.connect(self._process, SIGNAL("finished()"), self.stop)
        self.connect(self._process, SIGNAL("readyReadStandardOutput()"), self.__grep_std_out)
        self.set_default_widget_prop()

        self._stop_timer = QTimer(self)
        self._stop_timer.setSingleShot(True)
        self._stop_timer.setInterval(1000)
        self._stop_timer.timeout.connect(self._force_stop)

    @Slot()
    def _force_stop(self):
        os.kill(self._process.pid(), signal.SIGTERM)
        self._stopping = False
        if not self.is_started():
            self.started_signal.emit()
        super(VideoMediaView, self).stop()

    @Slot(object)
    def _process_error(self, err):
        self._errors.append(err)
        self.stop()

    @Slot()
    def play(self):
        self._finished = 0
        path = "%s/%s" % (self._save_dir, self._options['uri'])
        self._widget.show()
        args = [
            '-slave', '-identify', '-input',
            'nodefault-bindings:conf=/dev/null',
            '-wid', str(int(self._widget.winId())),
            path
        ]
        if self._mute:
            args += ['-ao', 'null']

        self._process.start('mplayer', args)
        self._stop_timer.start()

    @Slot()
    def stop(self, delete_widget=False):
        if self._stopping or self.is_finished():
            return False
        self._stop_timer.start()
        self._stopping = True
        if self._process.state() == QProcess.ProcessState.Running:
            self._process.write("quit\n")
            self._process.waitForFinished(50)
            self._process.close()

        super(VideoMediaView, self).stop(delete_widget)
        self._stopping = False
        self._stop_timer.stop()
        return True

    @Slot()
    def __grep_std_out(self):
        lines = self._process.readAllStandardOutput().split("\n")
        for line in lines:
            if not line.isEmpty():
                if line.startsWith("Starting playback"):
                    self._widget.raise_()
                    self._play_timer.start()
                    self.started_signal.emit()
                    self._stop_timer.stop()
                else:
                    part = line.split("=")
                    if 'ID_LENGTH' == part[0]:
                        if float(self._duration) > 0:  # user set the video duration manually.
                            self._play_timer.setInterval(int(1000 * float(self._duration)))
                        else:  # use duration found by mplayer.
                            self._play_timer.setInterval(int(1000 * float(part[1])))
Example #45
0
def parse_asn1(*files, **options):
    """ Call the ASN.1 parser on a number of files, and return the module
        containing the AST
        This function uses QProcess to launch the ASN.1 compiler because
        the subprocess module from Python has issues on the Windows platform
    """
    global AST

    ast_version = options.get("ast_version", ASN1.UniqueEnumeratedNames)
    rename_policy = options.get("rename_policy", ASN1.NoRename)
    flags = options.get("flags", [ASN1.AstOnly])
    assert isinstance(ast_version, ASN1)
    assert isinstance(rename_policy, ASN1)
    assert isinstance(flags, list)
    # if os.name == 'posix' and hasattr(sys, 'frozen'):
    # Frozen Linux binaries are expected to use the frozen ASN.1 compiler
    # No: there are issues with freezing the .NET applications - discard
    #     asn1exe = 'asn1scc'
    # else:
    #    asn1exe = 'asn1.exe'
    path_to_asn1scc = spawn.find_executable("asn1.exe")

    if not path_to_asn1scc:
        raise TypeError("ASN.1 Compiler not found in path")
    if os.name == "posix":
        path_to_mono = spawn.find_executable("mono")
        if not path_to_mono:
            raise TypeErorr('"mono" not found in path. Please install it.')
        binary = path_to_mono
        arg0 = path_to_asn1scc
    else:
        binary = path_to_asn1scc
        arg0 = ""
    asn1scc_root = os.path.abspath(os.path.dirname(path_to_asn1scc))
    # Create a temporary directory to store dataview.py and import it
    tempdir = tempfile.mkdtemp()
    sys.path.append(tempdir)
    if os.name == "nt":
        # On windows, remove the drive letter, workaround to ASN1SCC bug
        tempdir = tempdir[2:]
        asn1scc_root = asn1scc_root[2:]
    filename = str(uuid.uuid4()).replace("-", "_")
    filepath = tempdir + os.sep + filename + ".py"

    stg = asn1scc_root + os.sep + "python.stg"

    args = [
        arg0,
        "-customStgAstVerion",
        str(ast_version.value),
        "-customStg",
        stg + "::" + filepath,
        "-renamePolicy",
        str(rename_policy.value),
    ] + list(*files)
    asn1scc = QProcess()
    LOG.debug(os.getcwd())
    LOG.debug(binary + " " + " ".join(args))
    asn1scc.start(binary, args)
    if not asn1scc.waitForStarted():
        raise TypeError("Could not start ASN.1 Compiler")
    if not asn1scc.waitForFinished():
        raise TypeError("Execution of ASN.1 Compiler timed out")
    exitcode = asn1scc.exitCode()
    result = asn1scc.readAllStandardError()
    if exitcode != 0:
        raise TypeError("ASN.1 Compiler Error (exit code = {}) - {}".format(exitcode, str(result)))
    else:
        if filename in AST.viewkeys():
            # Re-import module if it was already loaded
            ast = AST[filename]
            reload(ast)
        else:
            ast = importlib.import_module(filename)
            AST[filename] = ast
        return ast
Example #46
0
def parse_asn1(*files, **options):
    ''' Call the ASN.1 parser on a number of files, and return the module
        containing the AST
        This function uses QProcess to launch the ASN.1 compiler because
        the subprocess module from Python has issues on the Windows platform
    '''
    # use basic caching to avoid re-parsing when loading the model
    project_cache = os.getenv ("PROJECT_CACHE")
    if project_cache is not None and not os.path.isdir(project_cache):
        raise TypeError (
            "The configured cache folder \""
            + project_cache + "\" is not there!\n")
    # make sure the same files are not parsed more than once if not modified
    filehash = hashlib.md5()
    file_list = sorted(list(*files))
    try:
        for each in file_list:
            filehash.update(open(each).read())
            # also hash the file path: it is used in the AST, so it is
            # not enough to hash the content of the ASN.1 files, as two sets
            # of input files may have the same hash
            filehash.update(each)
    except IOError as err:
        raise TypeError (str(err))
    new_hash = filehash.hexdigest()

    # names of the files that will be generated by asn1scc and then parsed
    out_py_name   = new_hash + ".py"
    out_html_name = new_hash + ".html"

    if new_hash in AST.viewkeys():
        return AST[new_hash]
    elif project_cache is not None:
        outdir = project_cache
    elif project_cache is None:
        outdir = tempfile.mkdtemp()

    # to allow the import
    sys.path.append(outdir)

    ast_version = options.get('ast_version', ASN1.UniqueEnumeratedNames)
    rename_policy = options.get('rename_policy', ASN1.NoRename)
    flags = options.get('flags', [ASN1.AstOnly])
    pprint = options.get('pretty_print', False)
    assert isinstance(ast_version, ASN1)
    assert isinstance(rename_policy, ASN1)
    assert isinstance(flags, list)
    path_to_asn1scc = spawn.find_executable('asn1.exe')

    if not path_to_asn1scc:
        raise TypeError('ASN.1 Compiler not found in path')
    if os.name == 'posix':
        path_to_mono = spawn.find_executable('mono')
        if not path_to_mono:
            raise TypeError('"mono" not found in path. Please install it.')
        binary = path_to_mono
        arg0 = path_to_asn1scc
    else:
        binary = path_to_asn1scc
        arg0 = ''
    asn1scc_root = os.path.abspath(os.path.dirname(path_to_asn1scc))

    if os.name == 'nt':
        # On windows, remove the drive letter, workaround to ASN1SCC bug
        outdir       = outdir[2:]
        asn1scc_root = asn1scc_root[2:]

    # The two possible files that can be generated with complete path:
    py_filepath   = outdir + os.sep + out_py_name
    html_filepath = outdir + os.sep + out_html_name

    # call the ASN.1 compiler only if there is no existing cached file
    if project_cache is None or not os.path.exists(py_filepath):
        stg = asn1scc_root + os.sep + 'python.stg'

        if pprint:
            # Generate an html file with pretty-printed ASN.1 types
            stg_qrc = QFile(':misc/pretty_print_asn1.stg')
            stg_qrc.open(1)
            content = stg_qrc.readAll()
            stgfile = outdir + os.sep + 'pretty_print_asn1.stg'
            with open(stgfile, 'w') as tmpfile:
                tmpfile.write(content.data())
            html = ['-customIcdUper', stgfile + '::' + html_filepath]
        else:
            html = []
        args = [arg0, '-customStgAstVersion', str(ast_version.value),
                '-customStg', stg + '::' + py_filepath,
                '-renamePolicy', str(rename_policy.value)] + html + file_list
        asn1scc = QProcess()
        LOG.debug(os.getcwd())
        LOG.debug(binary + ' ' + ' '.join(args))
        asn1scc.start(binary, args)

        _ = waitfor_qprocess(asn1scc, "ASN.1 Compiler")

    ast = importlib.import_module(new_hash)
    AST[new_hash] = ast
    if pprint:
        # add the path to the optionally-generated pretty-printed HTML file
        ast.html = html_filepath
    return ast
Example #47
0
class TestPython(object):
    def __init__(self, ID=None):
        self.Test = QProcess()
        self.ID = ID
        #a and b to test if i get a output or command error
        self.a = True
        self.Settings = QtCore.QSettings('Tyrant.cfg',
                                         QtCore.QSettings.IniFormat)

    def TestVersion(self):
        print('Test python version')
        self.Test.readyReadStandardError.connect(self.getOutput)
        self.Test.readyReadStandardOutput.connect(self.getOutput)
        if self.ID is not None:
            self.Test.error.connect(self.Error)
        #if i have a custom pythonpath, i'll use it here
        Res = Resources()
        Python = Res.getPref('Python')
        #test if is a pythonpath, if not open a default
        if len(Python) < 5:
            Python = 'python'
        self.Test.start(Python, ['-V'])
        self.Test.waitForFinished()
        self.Test.terminate()
        if (self.a is False) & (self.ID is None):
            #test a diferent command to run python 2.7
            a = self.TestVersion2()
            print a
            return a
        elif self.a:
            #say to program that python is working
            print('Python version found')
            self.Settings.setValue('Python/PythonPath', str(Python))
            self.Settings.sync()
            return True
        elif ((self.ID is not None) & (self.a is False)):
            return False

    def Error(self):
        self.a = False

    def TestVersion2(self):
        print('Testing python version 2')
        self.Test.readyReadStandardError.connect(self.getOutput)
        Python = 'python2.7'
        self.Test.start(Python, ['-V'])
        self.Test.waitForStarted()
        self.Test.waitForFinished()
        self.Test.terminate()
        if (self.a is False):
            #say thar python is not working
            return False
        else:
            self.Settings.setValue('Python/PythonPath', str(Python))
            self.Settings.sync()
            return True

    def getOutput(self):
        Out = str(self.Test.readAllStandardError())
        print(Out)
        if Out > 'Python 2.8':
            self.a = False
            return
        self.a = True
Example #48
0
 def __init__(self, patch=None, *args, **kwargs):        
     QProcess.__init__(self, *args, **kwargs)
     self.patch = None
def generate_completes(force=False):
    # check parsed functions
    cache_file = vex_settings.get_autocomplete_cache_file()
    if os.path.exists(cache_file) and not force:
        return True
    # get vcc
    vcc = os.path.join(hou.getenv('HFS'), 'bin', 'vcc').replace('/','\\')
    if os.name == 'nt':
        vcc = vcc + '.exe'
    if not os.path.exists(vcc):
        return False
    # generate new
    funcs = {}
    attrs = {}
    process = QProcess()
    process.start(' '.join([vcc, '-X']))
    process.waitForFinished()
    lines =  str(process.readAll()).split('\n')
    for context in lines:
        if context:
            process.start(' '.join([vcc, '-X', context]))
            process.waitForFinished()
            context_lines =  str(process.readAll())
            # variables
            variables = re.search(r'Global Variables:(.*)Control Statements:', context_lines, re.DOTALL)
            if variables:
                lines = variables.group(1).strip().split('\n')
                for l in lines:
                    s = l.split()
                    if len(s)==3:
                        attrs[s[-1]] = s[-2]
            # functions
            pat = r'^\s*(\w+\[?\]?)\s(\w+)(\(.+\))'
            for l in context_lines.split('\n'):
                func = re.findall(pat, str(l))
                if func:
                    if func[0][1] in funcs:
                        funcs[func[0][1]].append({'ret': func[0][0], 'args':func[0][2]})
                    else:
                        funcs[func[0][1]] = [{'ret': func[0][0], 'args':func[0][2]}]
    # save to cache
    if os.path.exists(cache_file):
        comp = json.load(open(cache_file))
    else:
        comp = {}
    comp['functions'] = funcs
    comp['attributes'] = attrs
    json.dump(comp, open(cache_file, 'w'), indent=4)
    return True
Example #50
0
class CfdConsoleProcess:
    """ Class to run a console process asynchronously, printing output and
    errors to the FreeCAD console and allowing clean termination in Linux
    and Windows """
    def __init__(self, finishedHook=None, stdoutHook=None, stderrHook=None):
        self.process = QProcess()
        self.finishedHook = finishedHook
        self.stdoutHook = stdoutHook
        self.stderrHook = stderrHook
        self.process.finished.connect(self.finished)
        self.process.readyReadStandardOutput.connect(self.readStdout)
        self.process.readyReadStandardError.connect(self.readStderr)
        self.print_next_error_lines = 0
        self.print_next_error_file = False

    def __del__(self):
        self.terminate()

    def start(self, cmd, env_vars=None, working_dir=None):
        """ Start process and return immediately """
        self.print_next_error_lines = 0
        self.print_next_error_file = False
        env = QtCore.QProcessEnvironment.systemEnvironment()
        if env_vars:
            for key in env_vars:
                env.insert(key, env_vars[key])
        self.process.setProcessEnvironment(env)
        if working_dir:
            self.process.setWorkingDirectory(working_dir)
        if platform.system() == "Windows":
            # Run through a wrapper process to allow clean termination
            cmd = [
                os.path.join(FreeCAD.getHomePath(), "bin", "python.exe"),
                '-u',  # Prevent python from buffering stdout
                os.path.join(os.path.dirname(__file__), "WindowsRunWrapper.py")
            ] + cmd
        print("Raw command: ", cmd)
        self.process.start(cmd[0], cmd[1:])

    def terminate(self):
        if platform.system() == "Windows":
            # terminate() doesn't operate and kill() doesn't allow cleanup and leaves mpi processes running
            # Instead, instruct wrapper program to kill child process and itself cleanly with ctrl-break signal
            self.process.write(b"terminate\n")
            self.process.waitForBytesWritten()  # 'flush'
        else:
            self.process.terminate()
        self.process.waitForFinished()

    def finished(self, exit_code):
        if self.finishedHook:
            self.finishedHook(exit_code)

    def readStdout(self):
        # Ensure only complete lines are passed on
        text = ""
        while self.process.canReadLine():
            byteArr = self.process.readLine()
            text += QTextStream(byteArr).readAll()
        if text:
            print(text, end='')  # Avoid displaying on FreeCAD status bar
            if self.stdoutHook:
                self.stdoutHook(text)
            # Must be at the end as it can cause re-entrance
            if FreeCAD.GuiUp:
                FreeCAD.Gui.updateGui()

    def readStderr(self):
        # Ensure only complete lines are passed on
        # Print any error output to console
        self.process.setReadChannel(QProcess.StandardError)
        text = ""
        while self.process.canReadLine():
            byteArr = self.process.readLine()
            text += QTextStream(byteArr).readAll()
        if text:
            if self.stderrHook:
                self.stderrHook(text)
            FreeCAD.Console.PrintError(text)
            # Must be at the end as it can cause re-entrance
            if FreeCAD.GuiUp:
                FreeCAD.Gui.updateGui()
        self.process.setReadChannel(QProcess.StandardOutput)

    def state(self):
        return self.process.state()

    def waitForStarted(self):
        return self.process.waitForStarted()

    def waitForFinished(self):
        # For some reason waitForFinished doesn't always return - so we resort to a failsafe timeout:
        while True:
            ret = self.process.waitForFinished(1000)
            if self.process.error() != self.process.Timedout:
                self.readStdout()
                self.readStderr()
                return ret
            if self.process.state() == self.process.NotRunning:
                self.readStdout()
                self.readStderr()
                return True

    def exitCode(self):
        return self.process.exitCode()

    def processErrorOutput(self, err):
        """
        Process standard error text output from OpenFOAM
        :param err: Standard error output, single or multiple lines
        :return: A message to be printed on console, or None
        """
        ret = ""
        errlines = err.split('\n')
        for errline in errlines:
            if len(errline) > 0:  # Ignore blanks
                if self.print_next_error_lines > 0:
                    ret += errline + "\n"
                    self.print_next_error_lines -= 1
                if self.print_next_error_file and "file:" in errline:
                    ret += errline + "\n"
                    self.print_next_error_file = False
                words = errline.split(' ',
                                      1)  # Split off first field for parallel
                FATAL = "--> FOAM FATAL ERROR"
                FATALIO = "--> FOAM FATAL IO ERROR"
                if errline.startswith(FATAL) or (len(words) > 1 and
                                                 words[1].startswith(FATAL)):
                    self.print_next_error_lines = 1
                    ret += "OpenFOAM fatal error:\n"
                elif errline.startswith(FATALIO) or (
                        len(words) > 1 and words[1].startswith(FATALIO)):
                    self.print_next_error_lines = 1
                    self.print_next_error_file = True
                    ret += "OpenFOAM IO error:\n"
        if len(ret) > 0:
            return ret
        else:
            return None
Example #51
0
class TestPython(object):

    def __init__(self, ID=None):
        self.Test = QProcess()
        self.ID = ID
        #a and b to test if i get a output or command error
        self.a = True
        self.Settings = QtCore.QSettings('Tyrant.cfg',
                                                    QtCore.QSettings.IniFormat)

    def TestVersion(self):
        print('Test python version')
        self.Test.readyReadStandardError.connect(self.getOutput)
        self.Test.readyReadStandardOutput.connect(self.getOutput)
        if self.ID is not None:
            self.Test.error.connect(self.Error)
        #if i have a custom pythonpath, i'll use it here
        Res = Resources()
        Python = Res.getPref('Python')
        #test if is a pythonpath, if not open a default
        if len(Python) < 5:
            Python = 'python'
        self.Test.start(Python, ['-V'])
        self.Test.waitForFinished()
        self.Test.terminate()
        if (self.a is False) & (self.ID is None):
            #test a diferent command to run python 2.7
            a = self.TestVersion2()
            print a
            return a
        elif self.a:
            #say to program that python is working
            print('Python version found')
            self.Settings.setValue('Python/PythonPath', str(Python))
            self.Settings.sync()
            return True
        elif ((self.ID is not None) & (self.a is False)):
            return False

    def Error(self):
        self.a = False

    def TestVersion2(self):
        print('Testing python version 2')
        self.Test.readyReadStandardError.connect(self.getOutput)
        Python = 'python2.7'
        self.Test.start(Python, ['-V'])
        self.Test.waitForStarted()
        self.Test.waitForFinished()
        self.Test.terminate()
        if (self.a is False):
            #say thar python is not working
            return False
        else:
            self.Settings.setValue('Python/PythonPath', str(Python))
            self.Settings.sync()
            return True

    def getOutput(self):
        Out = str(self.Test.readAllStandardError())
        print(Out)
        if Out > 'Python 2.8':
            self.a = False
            return
        self.a = True
Example #52
0
def generate_completes2(force=False):
    # check parsed functions
    cache_file = vex_settings.get_autocomplete_cache_file()
    if os.path.exists(cache_file) and not force:
        return True
    # get vcc
    vcc = os.path.join(hou.getenv('HFS'), 'bin', 'vcc').replace('/','\\')
    if os.name == 'nt':
        vcc = vcc + '.exe'
    if not os.path.exists(vcc):
        return False
    # generate new
    funcs = {}
    attrs = {}
    process = QProcess()
    process.start(' '.join([vcc, '-X']))
    process.waitForFinished()
    lines =  str(process.readAll()).split('\n')
    for context in lines:
        if context:
            process.start(' '.join([vcc, '-X', context]))
            process.waitForFinished()
            context_lines =  str(process.readAll())
            # variables
            variables = re.search(r'Global Variables:(.*)Control Statements:', context_lines, re.DOTALL)
            if variables:
                lines = variables.group(1).strip().split('\n')
                for l in lines:
                    s = l.split()
                    if len(s)==3:
                        attrs[s[-1]] = s[-2]
            # functions
            pat = r'^\s*(\w+\[?\]?)\s(\w+)(\(.+\))'
            for l in context_lines.split('\n'):
                func = re.findall(pat, str(l))
                if func:
                    if func[0][1] in funcs:
                        funcs[func[0][1]].append({'ret': func[0][0], 'args':func[0][2]})
                    else:
                        funcs[func[0][1]] = [{'ret': func[0][0], 'args':func[0][2]}]
    # save to cache
    if os.path.exists(cache_file):
        comp = json.load(open(cache_file))
    else:
        comp = {}
    comp['functions'] = funcs
    comp['attributes'] = attrs
    json.dump(comp, open(cache_file, 'w'))
    return True
Example #53
0
class VideoMediaView(MediaView):
    def __init__(self, media, parent):
        super(VideoMediaView, self).__init__(media, parent)
        self._widget = QWidget(parent)
        self._process = QProcess(self._widget)
        self._process.setObjectName('%s-process' % self.objectName())
        self._std_out = []
        self._errors = []
        self._stopping = False
        self._mute = False
        if 'mute' in self._options:
            self._mute = bool(int(self._options['mute']))

        self._widget.setGeometry(media['_geometry'])
        self.connect(self._process, SIGNAL("error()"), self._process_error)
        self.connect(self._process, SIGNAL("finished()"), self.stop)
        self.connect(self._process, SIGNAL("readyReadStandardOutput()"),
                     self.__grep_std_out)
        self.set_default_widget_prop()

        self._stop_timer = QTimer(self)
        self._stop_timer.setSingleShot(True)
        self._stop_timer.setInterval(1000)
        self._stop_timer.timeout.connect(self._force_stop)

    @Slot()
    def _force_stop(self):
        os.kill(self._process.pid(), signal.SIGTERM)
        self._stopping = False
        if not self.is_started():
            self.started_signal.emit()
        super(VideoMediaView, self).stop()

    @Slot(object)
    def _process_error(self, err):
        self._errors.append(err)
        self.stop()

    @Slot()
    def play(self):
        self._finished = 0
        path = "%s/%s" % (self._save_dir, self._options['uri'])
        self._widget.show()
        args = [
            '-slave', '-identify', '-input',
            'nodefault-bindings:conf=/dev/null', '-wid',
            str(int(self._widget.winId())), path
        ]
        if self._mute:
            args += ['-ao', 'null']

        self._process.start('mplayer', args)
        self._stop_timer.start()

    @Slot()
    def stop(self, delete_widget=False):
        if self._stopping or self.is_finished():
            return False
        self._stop_timer.start()
        self._stopping = True
        if self._process.state() == QProcess.ProcessState.Running:
            self._process.write("quit\n")
            self._process.waitForFinished(50)
            self._process.close()

        super(VideoMediaView, self).stop(delete_widget)
        self._stopping = False
        self._stop_timer.stop()
        return True

    @Slot()
    def __grep_std_out(self):
        lines = self._process.readAllStandardOutput().split("\n")
        for line in lines:
            if not line.isEmpty():
                if line.startsWith("Starting playback"):
                    self._widget.raise_()
                    self._play_timer.start()
                    self.started_signal.emit()
                    self._stop_timer.stop()
                else:
                    part = line.split("=")
                    if 'ID_LENGTH' == part[0]:
                        if float(
                                self._duration
                        ) > 0:  # user set the video duration manually.
                            self._play_timer.setInterval(
                                int(1000 * float(self._duration)))
                        else:  # use duration found by mplayer.
                            self._play_timer.setInterval(
                                int(1000 * float(part[1])))