def _thread_extract(self): """Extract the files in the file list one by one.""" # Extract 7z and rar whole archive - if it SOLID - extract one file is SLOW if self._type in (SEVENZIP, ) and _7z_exec is not None: cmd = [ _7z_exec, 'x', '-bd', '-p-', '-o' + self._dst, '-y', self._src ] proc = process.Process(cmd) proc.spawn() proc.wait() self._condition.acquire() for name in self._files: self._extracted[name] = True self._condition.notify() self._condition.release() if self._type in (RAR, ) and _rar_exec is not None: cwd = os.getcwd() os.chdir(self._dst) cmd = [ _rar_exec, 'x', '-kb', '-p-', '-o-', '-inul', '--', self._src ] proc = process.Process(cmd) proc.spawn() proc.wait() os.chdir(cwd) self._condition.acquire() for name in self._files: self._extracted[name] = True self._condition.notify() self._condition.release() else: for name in self._files: self._extract_file(name) self.close()
def _extract_file(self, name): """Extract the file named <name> to the destination directory, mark the file as "ready", then signal a notify() on the Condition returned by setup(). """ if self._stop: self.close() sys.exit(0) try: if self._type in (ZIP, SEVENZIP): dst_path = os.path.join(self._dst, name) if not os.path.exists(os.path.dirname(dst_path)): os.makedirs(os.path.dirname(dst_path)) new = open(dst_path, 'wb') if self._type == ZIP: new.write(self._zfile.read(name)) elif self._type == SEVENZIP: if Archive7z is not None: new.write(self._szfile.getmember(name).read()) else: if _7z_exec is not None: proc = process.Process([ _7z_exec, 'x', '-bd', '-p-', '-o' + self._dst, '-y', self._src, name ]) proc.spawn() proc.wait() else: print '! Could not find 7Z file extractor.' new.close() elif self._type in (TAR, GZIP, BZIP2): if os.path.normpath(os.path.join(self._dst, name)).startswith(self._dst): self._tfile.extract(name, self._dst) else: print '! Non-local tar member:', name, '\n' elif self._type == RAR: if _rar_exec is not None: proc = process.Process([ _rar_exec, 'x', '-kb', '-p-', '-o-', '-inul', '--', self._src, name, self._dst ]) proc.spawn() proc.wait() else: print '! Could not find RAR file extractor.' elif self._type == MOBI: dst_path = os.path.join(self._dst, name) self._mobifile.extract(name, dst_path) except Exception: # Better to ignore any failed extractions (e.g. from a corrupt # archive) than to crash here and leave the main thread in a # possible infinite block. Damaged or missing files *should* be # handled gracefully by the main program anyway. pass self._condition.acquire() self._extracted[name] = True self._condition.notify() self._condition.release()
def extract_file_io(self, chosen): """Extract the file named <name> to the destination directory, mark the file as "ready", then signal a notify() on the Condition returned by setup(). """ if os.path.exists(os.path.join(self._dst, chosen)): return cStringIO.StringIO( open(os.path.join(self._dst, chosen), 'rb').read()) if self._type == DIRECTORY: return cStringIO.StringIO( open(os.path.join(self._src, chosen), 'rb').read()) if self._type == ZIP: return cStringIO.StringIO(self._zfile.read(chosen)) elif self._type in [TAR, GZIP, BZIP2]: return cStringIO.StringIO(self._tfile.extractfile(chosen).read()) elif self._type == RAR: proc = process.Process( [_rar_exec, 'p', '-inul', '-p-', '--', self._src, chosen]) fobj = proc.spawn() return cStringIO.StringIO(fobj.read()) elif self._type == SEVENZIP: if Archive7z is not None: return cStringIO.StringIO( self._szfile.getmember(chosen).read()) elif _7z_exec is not None: proc = process.Process( [_7z_exec, 'e', '-bd', '-p-', '-so', self._src, chosen]) fobj = proc.spawn() return cStringIO.StringIO(fobj.read())
def start_fcfs(self): if threading.activeCount() >= 2: pass else: # validation self.preemptive.hide() self.fcfs.hide() self.validate_input() if self.flag is True: processes = [] if self.bt1_1.value() > 0: p = process.Process() p.p_id = "P1" p.arrival_time = self.at_1.value() p.burst_time = self.bt1_1.value() processes.append(p) if self.bt1_2.value() > 0: p = process.Process() p.p_id = "P2" p.arrival_time = self.at_2.value() p.burst_time = self.bt1_2.value() processes.append(p) if self.bt1_3.value() > 0: p = process.Process() p.p_id = "P3" p.arrival_time = self.at_3.value() p.burst_time = self.bt1_3.value() processes.append(p) if self.bt1_4.value() > 0: p = process.Process() p.p_id = "P4" p.arrival_time = self.at_4.value() p.burst_time = self.bt1_4.value() processes.append(p) if self.bt1_5.value() > 0: p = process.Process() p.p_id = "P5" p.arrival_time = self.at_5.value() p.burst_time = self.bt1_5.value() processes.append(p) self.algo = cpu_sched.Algo() self.algo.FCFS(processes) temp_row = () rows = [] for i in range(len(processes)): temp_row = ((processes[i].p_id, self.algo.tat[i], self.algo.wait_time[i])) rows.append(temp_row) self.data = rows self.start_thread()
def randomtest(seed, steps, turns, pid, name, bits, sign): random.seed(a=seed) results = numpy.array([]) results.resize((turns, )) outdir = 'randomtest-seed-{}'.format(seed) for test_num in range(turns): kp = round(random.uniform(0, 255), 3) ki = round(random.uniform(0, kp), 3) kd = round(random.uniform(0, ki), 3) pid.configure(kp, ki, kd, bits, sign) reference = refpid.refpid(kp, ki, kd, bits, sign) ref = process.Process(reference, steps, turns) dut = process.Process(pid, steps, turns) ref.run() dut.run() # Check for fit errf = numpy.square(numpy.subtract(ref.output, dut.output)) err = numpy.cumsum(errf) / numpy.arange( 1, ref.output.size + 1, dtype=float) chi2 = numpy.sum(errf) / ref.output.size results[test_num, ] = chi2 if chi2 > 1000: if not os.path.isdir(outdir): os.mkdir(outdir) outfile = os.path.join( outdir, "{}-p{}-i{}-d{}.png".format(name, kp, ki, kd)) setline = plt.plot(ref.setpoint, '', label='Setpoint') refline = plt.plot(ref.output, '', label='Reference') outline = plt.plot(dut.output, '', label='Output/Feedback') plt.legend(['Setpoint', 'Reference', 'Out/Feedback']) plt.xlabel('Time (Seconds)') plt.ylabel('Codes') plt.title('{} vs. Reference (p={} i={} d={})'.format( name, kp, ki, kd)) plt.savefig(outfile) plt.close() best = numpy.amin(results) worst = numpy.amax(results) med = numpy.median(results) print("Best: {} Worst: {} Median: {}".format(best, worst, med)) plt.hist(results) outfile = os.path.join(outdir, "{}-histogram.png".format(name)) plt.savefig(outfile) plt.show()
def test007_program_flash(): """Program the boot loader into FLASH memory""" global debug, psu, dvm, relay, flash_tries relay.set(RELAY_RESET) relay.set(RELAY_PROGRAM_FLASH) relay.set(RELAY_RXD) relay.set(RELAY_TXD) relay.update() def callback(s): global debug, psu, dvm, relay, flash_tries i = psu.current info('Supply current = %7.3f mA' % (1000 * i)) fail_if(0 == flash_tries, 'Too many reset attempts (No CPU response)') info(s.replace('\10', '')) # remove backspaces if 'Press Reset' == s.strip(): info('Resets remaining: %d' % flash_tries) relay.on(RELAY_RESET) time.sleep(RESET_TIME) relay.off(RELAY_RESET) flash_tries -= 1 flash_tries = 10 p = process.Process([ 'make', 'flash-mbr', 'FLASH_UPDATE=YES', 'BOOTLOADER_TTY=' + CPU_SERIAL, "SERIAL_NUMBER='" + serial_number + "'" ], callback) rc = p.run() fail_unless(rc, 'Flashing failed') relay.off(RELAY_PROGRAM_FLASH)
def test_Process_argv_with_spaces(self): logfile = "log.log" if os.path.exists(logfile): os.unlink(logfile) p = process.Process(['log space', 'hi there']) p.wait() output = open(logfile, 'r').readlines() self.failUnless(output[1:] == ['hi there\n'])
def __init__(self, path, current_yr=None, force_new_download=False, forms=['PF', 'EZ', 'Full'], backfill=2, tolerance=1000, do_validation=True, clear_old=True, partial_validation=True, get_from_sql=True, output_full=True): forms = [f.upper() for f in forms] self.forms = ['Full' if f == 'FULL' else f for f in forms] self.path = path self.force_new_download = force_new_download self.logger, self.start = self.start_logging(path, current_yr) self.data = data.Data(self, clear_old, get_from_sql, current_yr, backfill) self.process = process.Process(self) self.validate = validate.Validate(self, tolerance, do_validation, partial_validation) self.write = write.Write(self, output_full)
def build_ok(): self.info_label.set_text("Running computation ...") prefix = "==KAIRA==" def on_line(line, stream): if line.startswith(prefix): self.info_label.set_text("Running computation ... " + line[len(prefix):]) return True def on_exit(code): self.process = None self.stop_button.set_sensitive(False) self.start_button.set_sensitive(True) if code == 0: report_name = os.path.join( self.app.project.get_directory(), self.app.project.get_name() + ".kreport") self.app.load_report(report_name) self.info_label.set_text( "Computation finished, report opened") else: self.info_label.set_text("Computation failed") p = process.Process(build_config.get_executable_filename(), on_line, on_exit) p.cwd = self.app.project.get_directory() simconfig = self.app.project.get_simconfig() if simconfig.parameters_values is None: if not self.app.open_simconfig_dialog(): return parameters = ["-r{0}".format(simconfig.process_count)] parameters += [ "-p{0}={1}".format(k, v) for (k, v) in simconfig.parameters_values.items() ] if self.create_dot.get_active(): parameters.append("-Vdot") if self.analyze_deadlock.get_active(): parameters.append("-Vdeadlock") if self.analyze_transition_occurrence.get_active(): parameters.append("-Vtchv") if self.analyze_final_marking.get_active(): parameters.append("-Vfmarking") if self.analyze_cycles.get_active(): parameters.append("-Vcycle") if not self.por.get_active(): parameters.append("-Vdisable-por") p.start(parameters) self.process = p self.stop_button.set_sensitive(True)
def processing(self): _event_id = None _event_id = self.getEvent() if _event_id: if not self.db_scisola.EventExist(_event_id): print _event_id orig = origin.Origin() orig = self.getOriginInfo(_event_id, orig) # if event's info exist if orig.datetime and orig.magnitude and orig.depth: # two threshold requirements in order to run a new event if orig.magnitude >= self.settings.magnitude_threshold and \ inrange(self.settings.center_latitude, self.settings.center_longitude, orig.latitude, orig.longitude, self.settings.distance_range): _p = process.Process( origin=orig, settings=self.settings, station_list=[], db_scisola=self.db_scisola, save2DB=True, timeout=self.settings.process_timeout, delay=self.settings.process_delay, parent=self.parent) _p.start()
def background(): """Create a background process.""" new_process = process.Process(io_system, the_dispatcher, process.Type.background) the_dispatcher.add_process(new_process) return True
def main(frames, frameSize, inputFile, tMemoryMove): processesList = [] for line in inputFile: if (line[len(line) - 1] == '\n'): line = line[:len(line) - 1] arr = line.split(' ') p = process.Process() for i in range(len(arr)): if i == 0: p.name = arr[i] elif i == 1: p.size = int(arr[i]) else: time = arr[i].split('/') p.arrivalTimes.append(int(time[0])) p.endTimes.append(int(time[1])) processesList.append(p) ''' for i in processesList: print(i.name) for j in range(len(i.arrivalTimes)): print(i.arrivalTimes[j]) print(i.endTimes[j]) ''' processesList_copy = copy.deepcopy(processesList) FirstFit.main(frames, frameSize, processesList, tMemoryMove, True) resetProcesses(processesList) NextFit.main(frames, frameSize, processesList_copy, tMemoryMove) resetProcesses(processesList) BestFit.main(frames, frameSize, processesList, tMemoryMove, False) resetProcesses(processesList) NonContiguous.main(frames, frameSize, processesList, tMemoryMove, False)
def run_simulated_program(self, name, directory, simconfig, valgrind): def output(line, stream): self.console_write_output(line) return True if valgrind: program_name = "valgrind" parameters = [ "-q", name ] else: program_name = name parameters = [] parameters += [ "-s", "auto", "-b", "-r", str(simconfig.process_count) ] sprocess = process.Process(program_name, output) sprocess.cwd = directory # FIXME: Timeout other_params = [ "-p{0}={1}".format(k, v) for (k, v) in simconfig.parameters_values.items() ] first_line = sprocess.start_and_get_first_line(parameters + other_params) try: port = int(first_line) except ValueError: self.console_write("Simulated program return invalid first line: " + first_line, "error") return None, None return sprocess, port
def __init__(self, process_name='', process_id=0, script_folder='scripts', wait=True): if process_name: proc = process.Process(process_name, suspended=True) if not proc.create(): return process_id = proc.get_id() else: proc = None self._device = frida.get_local_device() self._device.on("child-added", self._on_child_added) self._device.on("child-removed", self._on_child_removed) self._device.on("output", self._on_output) self.script_folder = script_folder self._instrument(process_id) if proc: proc.resume() if wait: print( "[!] Ctrl+D on UNIX, Ctrl+Z on Windows/cmd.exe to detach from instrumented program.\n\n" ) sys.stdin.read() self.session.detach()
def test007_program_flash(): """Program the boot loader into FLASH memory""" global debug, psu, dvm, relay relay.set(RELAY_RESET) relay.set(RELAY_PROGRAM_FLASH) relay.set(RELAY_RXD) relay.set(RELAY_TXD) relay.update() def callback(s): global debug, psu, dvm, relay i = psu.current info('Supply current = %7.3f mA' % (1000 * i)) info(s.replace('\10', '')) # remove backspaces if 'Press Reset' == s.strip(): relay.on(RELAY_RESET) time.sleep(RESET_TIME) relay.off(RELAY_RESET) p = process.Process([ 'make', 'flash-test-jig', 'BOOTLOADER_TTY=' + CPU_SERIAL, "SERIAL_NUMBER='" + serial_number + "'" ], callback) rc = p.run() fail_unless(rc, 'Flashing failed') relay.off(RELAY_PROGRAM_FLASH)
def test_Process_simple_cmd(self): logfile = "log.log" if os.path.exists(logfile): os.unlink(logfile) p = process.Process('log hi there') p.wait() output = open(logfile, 'r').readlines() self.failUnless(output[1:] == ['hi\n', 'there\n'])
def datadir(self): """Returns the datadir of this LilyPond instance. Most times this is something like "/usr/share/lilypond/2.13.3/" If this method returns False, the datadir could not be determined. """ if not self.abscommand(): return False # First ask LilyPond itself. p = process.Process([self.abscommand(), '-e', "(display (ly:get-option 'datadir)) (newline) (exit)"]) @p.done.connect def done(success): if success: d = codecs.decode(p.process.readLine(), 'latin1', 'replace').strip('\n') if os.path.isabs(d) and os.path.isdir(d): self.datadir = d return # Then find out via the prefix. if self.prefix(): dirs = ['current'] if self.versionString(): dirs.append(self.versionString()) for suffix in dirs: d = os.path.join(self.prefix(), 'share', 'lilypond', suffix) if os.path.isdir(d): self.datadir = d return self.datadir = False _scheduler.add(p)
def interactive(): """Create an interactive process.""" new_process = process.Process(io_system, the_dispatcher, process.Type.interactive) the_dispatcher.add_process(new_process) return True
def fill_queue(queue, io_bbust, io_interrupt, choice): odd = False even = False all = False if choice == 1: odd = True if choice == 2: even = True if choice == 3: all = True arival_t = [] count = 0 arival_t.append(0) for eachprocess in range(no_of_process): count += 1 process_instance = process.Process() if ((eachprocess + 1) % 2 == 0 and even): process_instance.io_bust = io_bbust process_instance.io_interrupt_time = io_interrupt if ((eachprocess + 1) % 2 == 1 and odd): process_instance.io_bust = io_bbust process_instance.io_interrupt_time = io_interrupt process_instance.process_name = 'P' + str(eachprocess + 1) process_input(process_instance, all) arival_t.append(process_instance.arrival_time) while arival_t[count - 1] > arival_t[count]: print 'Again! {} Arrival must be greator then previous: ' \ .format(process_instance.process_name), process_instance.arrival_time = integer_input() arival_t[count] = process_instance.arrival_time queue.put(process_instance)
def spawnProcess(self, processProtocol, executable, args=(), env={}, path=None, uid=None, gid=None, usePTY=0, childFDs=None): args, env = self._checkProcessArgs(args, env) if platformType == 'posix': if usePTY: if childFDs is not None: raise ValueError("Using childFDs is not supported with usePTY=True.") return process.PTYProcess(self, executable, args, env, path, processProtocol, uid, gid, usePTY) else: return process.Process(self, executable, args, env, path, processProtocol, uid, gid, childFDs) elif platformType == "win32": if uid is not None or gid is not None: raise ValueError("The uid and gid parameters are not supported on Windows.") if usePTY: raise ValueError("The usePTY parameter is not supported on Windows.") if childFDs: raise ValueError("Customizing childFDs is not supported on Windows.") if win32process: from twisted.internet._dumbwin32proc import Process return Process(self, processProtocol, executable, args, env, path) else: raise NotImplementedError, "spawnProcess not available since pywin32 is not installed." else: raise NotImplementedError, "spawnProcess only available on Windows or POSIX."
def execute( inputFile, frames, frameSize, timeMove): procList = [] for i in inputFile: arrtimeIns = True if(i[len(i)-1] == '\n'): i = i[:len(i)-1] splitspace = i.split(' ') for j in splitspace: j.split("\t") termList = [] for sublist in splitspace: for term in range(0,len(sublist)): if (sublist[term] == ""): sublist.pop[term] termList.append(sublist) #print(termList) #sys.stdout.flush() p = process.Process() for j in range(len(termList)): if j == 0: p.name = termList[j] elif j == 1: try: p.size = int(termList[j]) except: print("Invalid size: Program Terminated") sys.exit() else: time = termList[j].split('/') try: p.arrTimes.append(int(time[0])) p.endTimes.append(int(time[1])) except: print("Invalid arrival or end times: Program Terminated") sys.exit() #print(procList) #sys.stdout.flush() procList.append(p) procList_copy = copy.deepcopy(procList) procList_copy_1 = copy.deepcopy(procList) procList_copy_2 = copy.deepcopy(procList) FirstFit(frames, frameSize, procList, timeMove, True) refresh(procList) #processes, t_mem_move, frame_size, frame NextFit(procList_copy,timeMove, frameSize, frames) refresh(procList) BestFit(frames, frameSize, procList_copy_1, timeMove, False) refresh(procList) NonContiguous(procList_copy_2, timeMove,frameSize, frames)
def test_Process_argv_with_spaces_new_console(self): logfile = "log.log" if os.path.exists(logfile): os.unlink(logfile) flags = process.Process.CREATE_NEW_CONSOLE p = process.Process(['log space', 'hi there'], flags=flags) p.wait() output = open(logfile, 'r').readlines() self.failUnless(output[1:] == ['hi there\n'])
def test_Process_simple_cmd_new_console(self): logfile = "log.log" if os.path.exists(logfile): os.unlink(logfile) flags = process.Process.CREATE_NEW_CONSOLE p = process.Process('log hi there', flags=flags) p.wait() output = open(logfile, 'r').readlines() self.failUnless(output[1:] == ['hi\n', 'there\n'])
def _get_rar_exec(): """Return the name of the RAR file extractor executable, or None if no such executable is found. """ for command in ('unrar', 'rar'): if process.Process([command]).spawn() is not None: return command return None
def findAllProcessesByWmi(self): ''' Find all processes running on the system @types: -> list(process.Process) @command: wmic process get commandLine, creationdate, executablepath, name, processId ''' provider = self._getWmiAgentProvider() queryBuilder = provider.getBuilder('Win32_Process') queryBuilder.addWmiObjectProperties('name', 'processId', 'commandLine', 'executablepath', 'creationdate', 'ParentProcessId') processes = [] agent = provider.getAgent() results = agent.getWmiData(queryBuilder) for item in results: name = item.name if not name: logger.warn("Skipped process without name. CommandLine: %s" % item.commandLine) continue pid = item.processId if pid == '-1' or not pid.isnumeric(): logger.debug( "Skipped process '%s'. It is system process or has non numeric PID" % name) continue commandLine = self.__fixMissedProcessNameInCommandLine( name, item.commandLine) process = process_module.Process(name, pid, commandLine=commandLine) process.executablePath = item.executablepath parentPid = item.ParentProcessId if parentPid and parentPid.isdigit(): process.setParentPid(parentPid) processStartupTimeString = item.creationdate if processStartupTimeString: try: startupDate = modeling.getDateFromUtcString( processStartupTimeString) process.setStartupTime(startupDate) except: logger.debug("Failed parsing date from UTC string '%s'" % processStartupTimeString) argsMatch = re.match('("[^"]+"|[^"]\S+)\s+(.+)$', process.commandLine) if argsMatch: process.argumentLine = argsMatch.group(2) processes.append(process) return processes
def generate_randomly(self, number): print("\n\nCreating {} Processes\n\n".format(number)) for i in range(number): priority = 0 arrival_time = randint(0, self.duration) duration_time = randint(0, self.duration) cpu_bound = bool(random.getrandbits(1)) user_level = bool(random.getrandbits(1)) if user_level: priority = randint(1,4) tmp_process = process.Process(arrival_time=arrival_time, priority=priority, duration_time=duration_time, user_level=user_level, process_id=i, cpu_bound=cpu_bound) self.submission_queue.append(tmp_process) else: tmp_process = process.Process(arrival_time=arrival_time, priority=priority, duration_time=duration_time, user_level=user_level, process_id=i, cpu_bound=cpu_bound) self.submission_queue.append(tmp_process) self.show_processes() return
def generate_manualy(self, number): print("\n\nCreating {} Processes\n\n".format(number)) for i in range(number): priority = 0 arrival_time = int(input("Arrival Time: ")) duration_time = int(input("Duration Time: ")) cpu_bound = bool(input("CPU Bound? (true or false): ")) user_level = bool(input("User Level Process? (true or false): ")) if user_level: priority = int(input("Priority 1 a 3: ")) tmp_process = process.Process(arrival_time=arrival_time, priority=priority, duration_time=duration_time, user_level=user_level, process_id=i, cpu_bound=cpu_bound) self.submission_queue.append(tmp_process) else: tmp_process = process.Process(arrival_time=arrival_time, priority=priority, duration_time=duration_time, user_level=user_level, process_id=i, cpu_bound=cpu_bound) self.submission_queue.append(tmp_process) #self.show_processes() return
def move(self, option): if option == 1: kill = process.Process(self.ing).attack() self.ed[u"血量"] = self.ed[u"血量"] + kill return self.ed, 3 #前面的为返回了被作用者的属性,后面的为返回属性值的归属标识(3为承受者,2为施加者) elif option == 2: destory = process.Process(self.ing).manadestory() self.ed[u"血量"] = self.ed[u"血量"] + destory return self.ed, 3 elif option == 3: armor = process.Process(self.ing).define() self.ing[u"血量"] = self.ing[u"血量"] + armor return self.ing, 2 elif option == 4: final = process.Process(self.ing).run() if final == "success": self.ed[u"血量"] = 0 print "\n" print u"**************************************" print u"*************逃跑成功*****************" print u"**************************************" elif final == "fail": print "\n" print u"**************************************" print u"*************逃跑失败*****************" print u"**************************************" return self.ed, 3
def spawnProcess(self, processProtocol, executable, args=(), env={}, path=None, usePTY=0): """Spawn a process.""" return process.Process(self, processProtocol, executable, args, env, path)
def background(): """Create a background process.""" # creating a new process, assigning a io, same dispatcher, given type background new_process = process.Process(io_system, the_dispatcher, process.Type.background) # adds the process to the stack of runnable processes the_dispatcher.add_process(new_process) return True