def new_priority(priority=1): """Context manager to execute a with clause as a different priority.""" pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) original_priority = win32process.GetPriorityClass(handle) win32process.SetPriorityClass(handle, priorityclasses[priority]) try: yield # execute with-statement here finally: win32process.SetPriorityClass(handle, original_priority)
def main(): global ui global MainWindow global Ui_MainWindow pid = win32api.GetCurrentProcessId() print(pid, "<----Process ID") handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.HIGH_PRIORITY_CLASS) app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() dimCameraLiink = "rtsp://*****:*****@10.152.235.180" ocrCameraLink = "rtsp://*****:*****@10.152.235.184/ch1-s1?tcp" #10.152.235.184 t1 = threading.Thread(target=slabDim, args=(dimCameraLiink, )) t2 = threading.Thread(target=ocr, args=(ocrCameraLink, )) #t3 = threading.Thread(target = uiocrView,args=(ocrCameraLink,)) t1.start() t2.start() #t3.start() sys.exit(app.exec_()) t1.join() t2.join() #t3.join() print("Done with both the Threads................")
def _try_raise_self_process_priority(): """ Attempts to raise the priority level of the current process. Tries several methods depending on the platform; does nothing if unsuccessful. """ # https://stackoverflow.com/a/6245096/1007777 if RUNNING_ON_WINDOWS: try: # noinspection PyUnresolvedReferences import win32api # noinspection PyUnresolvedReferences import win32process # noinspection PyUnresolvedReferences import win32con handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, win32api.GetCurrentProcessId()) win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS) _logger.info('Windows process priority changed successfully using the win32 API modules') except ImportError: # noinspection PyUnresolvedReferences import psutil psutil.Process(os.getpid()).nice(psutil.REALTIME_PRIORITY_CLASS) _logger.info('Windows process priority changed successfully using the psutil module') else: new_niceness = os.nice(NICENESS_INCREMENT) _logger.info('POSIX process has been reniced successfully; new niceness %r', new_niceness)
def processPriority(priority=1): """Context manager to execute a with clause as a different priority.""" priorityclasses = [win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS] pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) original_priority = win32process.GetPriorityClass(handle) win32process.SetPriorityClass(handle, priorityclasses[priority]) try: yield # execute with-statement here finally: win32process.SetPriorityClass(handle, original_priority)
def process_pro(): import win32api import win32process import win32con pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS)
def lowpriority(): """ Set the priority of the process to below-normal. Copied from: http://stackoverflow.com/questions/1023038/change-process-priority-in-python-cross-platform""" try: sys.getwindowsversion() except: isWindows = False else: isWindows = True try: if isWindows: # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ import win32api, win32process, win32con pid = os.getpid() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass( handle, win32process.BELOW_NORMAL_PRIORITY_CLASS) win32api.CloseHandle(handle) else: # Unix and Mac should have a nice function os.nice(1) except: logger = logging.getLogger(__name__ + '.lowpriority') if not logger is None: logger.warn("Could not lower process priority") if isWindows: logger.warn( "Are you missing Win32 extensions for python? http://sourceforge.net/projects/pywin32/" ) pass
def setProcessPriorityIdle(): """ Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the priority of the current python process but can take any valid process ID. """ if os.name.lower().find('nt') != 0: os.nice(19) return try: import win32api, win32process, win32con priorityclasses = [ win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS ] pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityclasses[0]) except ImportError: pass
def main(): global ui global MainWindow global Ui_MainWindow pid = win32api.GetCurrentProcessId() print(pid, "<----Process ID") handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.HIGH_PRIORITY_CLASS) app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() dimCameraLiink = "C:/Users/shrin/Pictures/ocr_collection.mp4" ocrCameraLink = "C:/Users/shrin/Pictures/slab_collection.mp4" #10.152.235.184 t1 = threading.Thread(target=slabDim, args=(dimCameraLiink, )) t2 = threading.Thread(target=ocr, args=(ocrCameraLink, )) t1.start() t2.start() sys.exit(app.exec_()) t1.join() #t2.join() print("Done with both the Threads................")
def setPriority(self, pid=None, priority=2): """ Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the priority of the current python process but can take any valid process ID. """ import win32api, win32process, win32con priorityClasses = [ win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS ] threadPriorities = [ win32process.THREAD_PRIORITY_IDLE, #win32process.THREAD_PRIORITY_ABOVE_IDLE, #win32process.THREAD_PRIORITY_LOWEST, win32process.THREAD_PRIORITY_BELOW_NORMAL, win32process.THREAD_PRIORITY_NORMAL, win32process.THREAD_PRIORITY_ABOVE_NORMAL, win32process.THREAD_PRIORITY_HIGHEST, win32process.THREAD_PRIORITY_TIME_CRITICAL ] pid = win32api.GetCurrentProcessId() tid = win32api.GetCurrentThread() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityClasses[priority]) win32process.SetThreadPriority(tid, threadPriorities[priority]) if Config.get('performance', 'restrict_to_first_processor'): win32process.SetProcessAffinityMask(handle, 1)
def setpriority(pid=None, priority=1): """ Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the priority of the current python process but can take any valid process ID. """ priorityclasses = [ win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS ] if pid == None: #pid = win32api.GetCurrentProcessId() pid = ctypes.windll.kernel32.GetCurrentProcessId() handle = ctypes.windll.kernel32.OpenProcess( win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityclasses[priority]) ## Chris win32process.SetProcessPriorityBoost(handle, False) ct = ctypes.windll.kernel32.GetCurrentThread() gle = win32api.GetLastError() print("gct", win32api.FormatMessage(gle)) ctypes.windll.kernel32.SetThreadPriority( ct, win32con.THREAD_BASE_PRIORITY_LOWRT)
def lowpriority(): """ Set the priority of the process to below-normal.""" import sys try: sys.getwindowsversion() except: isWindows = False else: isWindows = True if isWindows: # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ import win32api, win32process, win32con pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS) else: import os os.nice(1)
def Interfacer(InterfacerQueue, TerminationCommander): import os CLS = lambda: os.system('cls') Epoch = 0 PID = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, PID) win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS) while True: GOT = [] while len(GOT) < 4: GOT.append(InterfacerQueue.get()) AllCosts = {} for n in GOT: AllCosts[n[0]] = n[1] Done = [True for x in AllCosts.itervalues() if x <= 80] CLS() print 'Alpha: ' + str(AllCosts[1]) print 'Beta: ' + str(AllCosts[2]) print 'Gamma: ' + str(AllCosts[3]) print 'Delta: ' + str(AllCosts[4]) print 'Epoch: ' + str(Epoch) Epoch += 1 if any(Done): TerminationCommander.put(1) break
def exec_cmd(cmd, nice=20, wait=True): """ Execute a child process from command in a new process :param list|str cmd: sequence of program arguments or a single string. On Unix single string is interpreted as the path of the program to execute, but it's only working if not passing arguments to the program. :param int nice: *Default: 20 * process priority to bet set (Unix only). For windows lowest priority is always set. :param bool wait: *Default: True* if True, program will wait for child process to terminate :return: """ if is_windows(): pc = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=DEVNULL) stdout, stderr = pc.communicate() import win32process import win32api import win32con handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pc.pid) win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS) else: pc = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pc.communicate() if wait: pc.wait() print(str(stderr) + "\n" + str(stdout))
def lowpriority(): """ Set the priority of the process to below-normal. http://stackoverflow.com/questions/1023038/change-process-priority-in-python-cross-platform """ pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.BELOW_NORMAL_PRIORITY_CLASS)
def set_realtime(): import win32api, win32process promote_admin() # pid = win32api.GetCurrentProcessId() # handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) # win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS) win32process.SetPriorityClass(win32api.GetCurrentProcess(), win32process.REALTIME_PRIORITY_CLASS)
def low_priority(): """Sets process (and its children) to have a very low priority.""" if WINDOWS: import win32api, win32con, win32process pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS) else: os.nice(19)
def _set_idle(): try: sys.getwindowsversion() import win32api, win32process, win32con pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS) except: os.nice(20)
def setPriorityWindows(pid, tipo): dic = { VERYLOW: win32process.IDLE_PRIORITY_CLASS, LOW: win32process.BELOW_NORMAL_PRIORITY_CLASS, HIGH: win32process.ABOVE_NORMAL_PRIORITY_CLASS, VERYHIGH: win32process.HIGH_PRIORITY_CLASS } handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, dic[tipo])
def _raise_self_process_priority(): if RUNNING_ON_WINDOWS: import win32api import win32process import win32con handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, win32api.GetCurrentProcessId()) win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS) else: import os os.nice(IO_PROCESS_NICENESS_INCREMENT)
def setProcessPriorityByPID(self,pid,pClass): if (isinstance(pClass,int)): pHand = win32api.OpenProcess(win32con.PROCESS_SET_INFORMATION, 0, pid) if (pHand): win32process.SetPriorityClass(pHand,pClass) else: print >>sys.stderr, '(%s).WARNING :: Unable to get the process handler for PID of "%s".' % (ObjectTypeName.objectSignature(self),pid) win32api.CloseHandle(pHand) else: print >>sys.stderr, '(%s).ERROR :: Unable to determine how to handle the pClass of "%s" which is of type "%s".' % (ObjectTypeName.objectSignature(self),pClass,type(pClass))
def lowerCurrentProcessPriority(): if xpybuild.buildcommon.IS_WINDOWS: import win32process, win32api,win32con win32process.SetPriorityClass(win32api.GetCurrentProcess(), win32process.BELOW_NORMAL_PRIORITY_CLASS) else: # on unix, people may run nice before executing the process, so # only change the priority unilaterally if it's currently at its # default value if os.nice(0) == 0: os.nice(1) # change to 1 below the current level
def _set_process_priority(self): """ Changes the process priority """ if sys.platform.startswith("win"): try: import win32api import win32con import win32process except ImportError: log.error( "pywin32 must be installed to change the priority class for QEMU VM {}" .format(self._name)) else: log.info( "setting QEMU VM {} priority class to BELOW_NORMAL".format( self._name)) handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, self._process.pid) if self._process_priority == "realtime": priority = win32process.REALTIME_PRIORITY_CLASS elif self._process_priority == "very high": priority = win32process.HIGH_PRIORITY_CLASS elif self._process_priority == "high": priority = win32process.ABOVE_NORMAL_PRIORITY_CLASS elif self._process_priority == "low": priority = win32process.BELOW_NORMAL_PRIORITY_CLASS elif self._process_priority == "very low": priority = win32process.IDLE_PRIORITY_CLASS else: priority = win32process.NORMAL_PRIORITY_CLASS win32process.SetPriorityClass(handle, priority) else: if self._process_priority == "realtime": priority = -20 elif self._process_priority == "very high": priority = -15 elif self._process_priority == "high": priority = -5 elif self._process_priority == "low": priority = 5 elif self._process_priority == "very low": priority = 19 else: priority = 0 try: process = yield from asyncio.create_subprocess_exec( 'renice', '-n', str(priority), '-p', str(self._process.pid)) yield from process.wait() except (OSError, subprocess.SubprocessError) as e: log.error( 'Could not change process priority for QEMU VM "{}": {}'. format(self._name, e))
def top_priority(): """ Set the priority of the process to above-normal.""" if os.name == 'posix': os.nice(19) else: import win32api, win32process, win32con pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS)
def HighPriority(): """ Set the priority of the process to the highest level.""" if isWindows: # Based on: # "Recipe 496767: Set Process Priority In Windows" on ActiveState # http://code.activestate.com/recipes/496767/ pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS) else: os.nice( -os.nice(0) )
def priority(self, p = None): if (p == None): return(self.__priority) table = {'NORMAL' : win32con.NORMAL_PRIORITY_CLASS, 'HIGH' : win32con.HIGH_PRIORITY_CLASS} win32process.SetPriorityClass(win32api.GetCurrentProcess(), table[p]) self.__priority = p
def reduce_process_priority(self, process_id): if sys.platform == "win32": # Needs pywin32... http://sourceforge.net/projects/pywin32/files/pywin32/ try: import win32api, win32process, win32con handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, process_id) win32process.SetPriorityClass( handle, win32process.BELOW_NORMAL_PRIORITY_CLASS) except Exception, e: print("\n Failed to set subprocess priority:", e)
def setpriority(pid=None,priority=1): priorityclasses = [win32process.IDLE_PRIORITY_CLASS, win32process.BELOW_NORMAL_PRIORITY_CLASS, win32process.NORMAL_PRIORITY_CLASS, win32process.ABOVE_NORMAL_PRIORITY_CLASS, win32process.HIGH_PRIORITY_CLASS, win32process.REALTIME_PRIORITY_CLASS] if pid == None: pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityclasses[priority])
def setpriority(pid=None, priority=1): """Set The Priority of a Windows Process. Priority is a value between 0-5 where 2 is normal priority. Default sets the priority of the current python process but can take any valid process ID. """ if pid == None: pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, priorityclasses[priority])
def generate_main(queue: mp.Queue, worker_id, start, step, n): print("[Worker %d] Spawn" % (worker_id, )) wp.SetProcessAffinityMask(-1, 1 << worker_id) wp.SetPriorityClass(-1, 0x00000040 | 0x00100000) for i_sample in range(start, n, step): freq_low, freq_high = sorted( np.random.uniform(band_freq_list[0], band_freq_list[-1], size=2)) rd_low, rd_high = sorted(np.random.uniform(0.3, 3.0, size=2)) disto_low, disto_high = sorted(np.random.uniform(0.0, 0.1, size=2)) energy_low, energy_high = sorted(np.random.uniform(0.025, 1.0, size=2)) magn_low, magn_high = sorted(np.random.uniform(0.025, 1.0, size=2)) snr_low, snr_high = np.exp( sorted(np.random.uniform(np.log(8), np.log(1e16), size=2))) ''' rd_low, rd_high = 3.0, 3.0 disto_low, disto_high = 0.0, 0.1 energy_low, energy_high = 1.0, 1.0 magn_low, magn_high = 1.0, 1.0 snr_low, snr_high = 8, 8 ''' use_shape_noise = (np.random.randint(0, 2) == 1) n_extend_hop = np.random.randint(0, 32) #print("S0") osr = np.random.choice(gvm_osr_list) f0_list, w = generate_sample_0(freq_low, freq_high, rd_low, rd_high, disto_low, disto_high, energy_low, energy_high, magn_low, magn_high, snr_low, snr_high, use_shape_noise, osr, n_hop_per_sample + n_extend_hop) cut_begin = np.random.randint(0, n_extend_hop + 1) f0_list = f0_list[cut_begin:cut_begin + n_hop_per_sample] #print("S1") feature_list = generate_sample_1(w)[cut_begin:cut_begin + n_hop_per_sample] queue.put((i_sample, f0_list, feature_list)) ''' pl.figure() pl.imshow(feature_list[:, :, 1].T, interpolation='nearest', aspect='auto', origin='lower', cmap="plasma") pl.plot((freqToBark(f0_list) - band_start) / (band_stop - band_start) * n_band) pl.figure() pl.imshow(feature_list[:, :, 2].T, interpolation='nearest', aspect='auto', origin='lower', cmap="plasma") pl.plot((freqToBark(f0_list) - band_start) / (band_stop - band_start) * n_band) pl.figure() pl.imshow(feature_list[:, :, 3].T, interpolation='nearest', aspect='auto', origin='lower', cmap="plasma", vmin=band_freq_list[0] / sr, vmax=band_freq_list[-1] / sr) pl.plot((freqToBark(f0_list) - band_start) / (band_stop - band_start) * n_band) pl.show() ''' queue.put(worker_id)
def _set_idle(): if 'linux' in sys.platform: os.nice(20) else: try: sys.getwindowsversion() import win32api,win32process,win32con # @UnresolvedImport pid = win32api.GetCurrentProcessId() handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid) win32process.SetPriorityClass(handle, win32process.IDLE_PRIORITY_CLASS) except: #Windows 64-bit pass