示例#1
0
	def Query(self, object, counter, instance = None, machine = None):
		try:
			return win32pdhutil.GetPerformanceAttributes(object, counter, instance, machine=machine)
		except win32pdhutil.error as exc:
			raise exception.Exception(desc=exc.strerror)
		except TypeError as desc:
			raise exception.Exception(desc=desc,scode=winerror.DISP_E_TYPEMISMATCH)
示例#2
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
示例#3
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
示例#4
0
文件: perfmon.py 项目: beiske/play
 def Query(self, object, counter, instance=None, machine=None):
     try:
         return win32pdhutil.GetPerformanceAttributes(object,
                                                      counter,
                                                      instance,
                                                      machine=machine)
     except win32pdhutil.error, (rc, fn, desc):
         raise exception.Exception(desc=desc)
示例#5
0
    def prepare_for_run(self, config, year, check_tcw_process=False):
        """before calling travel model macro, check if transcad GUI is running, 
        if not, try to start transcad binary process"""
        ## TODO: TransCAD COM server is very picky about tcw.exe process in memory
        ## as of April 2007, a tcw process started by python won't work
        ## so manually start TransCAD program is needed before running this script

        set_project_ini_file(config, year)
        if not check_tcw_process:
            return

        cmdline = config['transcad_binary']
        head, tail = os.path.split(cmdline)
        procname, ext = os.path.splitext(tail)  #tcw

        kill_process = False
        start_program = False
        tc_program_classname = "tcFrame"  #ClassName for TransCAD program
        try:
            hwnd = win32gui.FindWindow(tc_program_classname, None)
        except:
            start_program = True  # No Transcand Window found, we'll need to start TransCAD program
        else:
            try:
                #first check if tcw process is in memory
                win32pdhutil.GetPerformanceAttributes('Process', 'ID Process',
                                                      procname)
                pids = win32pdhutil.FindPerformanceAttributesByName(procname)
                for pid in pids:
                    win32process.TerminateProcess(pid)
                start_program = True
            except:
                raise RuntimeError, "Unable to kill TransCAD process in memory"

        ##transcad not started, try to start it
        if start_program:
            try:
                pass
                cmdline = win32api.GetShortPathName(cmdline)
                cmdline = cmdline + " -q"
                os.system('start /B "start TransCAD" ' +
                          cmdline)  #start TransCAD in background
                time.sleep(9)
                #procHandles = win32process.CreateProcess(None, cmdline, None, None, 0, 0, None, None,
                #win32process.STARTUPINFO())
                #self.hProcess, hThread, PId, TId = procHandles
            except:
                logger.log_error(
                    "Unable to start TransCAD in %s; it must be running to invoke travel model macro."
                    % cmdline)
                sys.exit(1)
示例#6
0
def haveProc(procname):
    """ Tests if procname is running. """
    try:
        win32pdhutil.GetPerformanceAttributes('Process', 'ID Process', procname)
    except:
        pass

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

    if len(pids) == 0:
        return 0
    else:
        return 1
示例#7
0
    def PerformanceSnapshot(self):
        """
        This method grabs a snapshot of relevent system information to report
        it. This helps track the effect of the AG Toolkit on the system.
        """
        import win32pdhutil
        perfData = dict()
        counterGroup = "Process(python)"
        counterNames = [
            "% Processor Time", "% User Time", "Handle Count", "Private Bytes",
            "Thread Count", "% Processor Time"
        ]

        for n in counterNames:
            key = "%s.%s" % (counterGroup, n)
            perfData[key] = win32pdhutil.GetPerformanceAttributes(
                counterGroup, n)

        return perfData
示例#8
0
        def _GetProcessIdByName(self, name):
            """
            Try and get pid for a process by name.
            """

            try:
                win32pdhutil.GetPerformanceAttributes('Process', 'ID Process',
                                                      name)
            except:
                sys.stdout.write("Memory: Unable to locate process [%s]\n" %
                                 name)
                raise

            pids = win32pdhutil.FindPerformanceAttributesByName(name)

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

            return pids[0]
示例#9
0
import win32pdhutil, win32pdh, wmi, win32api, win32process
c = wmi.WMI(
)  #<-- this takes a ling time to set up. but after this initialiseation it is very quick

#to get a process's attributes you have to name them
a = str(
    win32pdhutil.FindPerformanceAttributesByName("explorer",
                                                 counter="Virtual Bytes"))

print "Explorer virtual Bytes: ", a  #will give you virtual bytes

#to get system you do it slightly differently
z = str(win32pdhutil.GetPerformanceAttributes("Memory", "Page Faults/sec"))

print "memory Page Faults", z  # will give you memory page faults a second

#Now here is the fun bit to get the process's cpu-usage is very difficult
# it is not simple like i thought this
cpu = str(
    win32pdhutil.FindPerformanceAttributesByName("explorer",
                                                 counter="% Processor Time"))
print "Explorer CPU Time is: ", cpu

#after searching high and low on the internet i finally found how to do it using WMI (so windows only)
process_info = {}
for p in c.Win32_PerfRawData_PerfProc_Process(name='explorer'):
    n1, d1 = long(p.PercentProcessorTime), long(p.Timestamp_Sys100NS)
    n0, d0 = process_info.get(id, (0, 0))

    try:
        percent_processor_time = (float(n1 - n0) / float(d1 - d0)) * 100.0