def get_output(cmd): if isinstance(cmd, list): cmd = ' '.join(cmd) process = QProcess() process.start(cmd) process.waitForFinished() return str(process.readAll())
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)
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)
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 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: f_name = func[0][1] f_args = func[0][2] if f_name in funcs: if not f_args in funcs[f_name].get('args', []): funcs[f_name]['args'].append(f_args) else: funcs[f_name] = {'args': [f_args]} # parse help if Houdini 15 if hou.applicationVersion()[0] >= 15: funcs = parse_help(funcs) # 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
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 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 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
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"
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)
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)
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')
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()
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...."
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()
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)
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
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
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])))
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 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) #---- kong ---- for RPi self.rect = media['geometry'] self.omxplayer = True #---- @Slot() def process_timeout(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): print '---- process error ----' self.errors.append(err) self.stop() @Slot() def process_finished(self): self.stop() @Slot() def process_started(self): self.stop_timer.stop() if float(self.duration) > 0: self.play_timer.setInterval(int(float(self.duration) * 1000)) self.play_timer.start() self.started_signal.emit() pass @Slot() def play(self): self.finished = 0 self.widget.show() self.widget.raise_() path = '%s/%s' % (self.save_dir, self.options['uri']) #---- kong ---- if self.omxplayer is True: left, top, right, bottom = self.rect.getCoords() rect = '%d,%d,%d,%d' % (left, top, right, bottom) args = ['--win', rect, '--no-osd', '--layer', self.zindex, path] self.process.start('omxplayer.bin', args) self.stop_timer.start() else: args = [ '-slave', '-identify', '-input', 'nodefault-bindings:conf=/dev/null', '-wid', str(int(self.widget.winId())), path ] self.process.start('mplayer', args) self.stop_timer.start() #---- @Slot() def stop(self, delete_widget=False): #---- kong ---- if not self.widget: return False if self.stopping or self.is_finished(): return False self.stop_timer.start() self.stopping = True if self.process.state() == QProcess.ProcessState.Running: if self.omxplayer is True: self.process.write('q') else: self.process.write('quit\n') self.process.waitForFinished() self.process.close() super(VideoMediaView, self).stop(delete_widget) self.stopping = False self.stop_timer.stop() return True
class WebMediaView(MediaView): 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() @Slot() def process_timeout(self): os.kill(self.process.pid(), signal.SIGTERM) self.stopping = False if not self.is_started(): self.started_signal.emit() super(WebMediaView, self).stop() @Slot(object) def process_error(self, err): print '---- process error ----' self.errors.append(err) self.stop() @Slot() def process_finished(self): self.stop() @Slot() def process_started(self): self.stop_timer.stop() if float(self.duration) > 0: self.play_timer.setInterval(int(float(self.duration) * 1000)) self.play_timer.start() self.started_signal.emit() pass @Slot() def play(self): self.finished = 0 self.widget.show() self.widget.raise_() #---- kong ---- url = self.options['uri'] args = [ #'--kiosk', str(self.rect.left()), str(self.rect.top()), str(self.rect.width()), str(self.rect.height()), QUrl.fromPercentEncoding(url) ] #self.process.start('chromium-browser', args) self.process.start('./dist/web', args) self.stop_timer.start() #---- @Slot() def stop(self, delete_widget=False): #---- kong ---- if not self.widget: return False if self.stopping or self.is_finished(): return False self.stop_timer.start() self.stopping = True if self.process.state() == QProcess.ProcessState.Running: #os.system('pkill chromium') os.system('pkill web') self.process.waitForFinished() self.process.close() super(WebMediaView, self).stop(delete_widget) self.stopping = False self.stop_timer.stop() return True
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])))
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