<commit_before>#!/usr/bin/env python
#
# $Id$
#

"""psutil is a module providing convenience functions for managing
processes in a portable way by using Python.
"""

__version__ = "0.2.0"
version_info = tuple([int(num) for num in __version__.split('.')])

__all__ = [
    # exceptions
    "Error", "NoSuchProcess", "AccessDenied",
    # constants
    "NUM_CPUS", "TOTAL_PHYMEM", "version_info", "__version__",
    # classes
    "Process",
    # functions
    "test", "pid_exists", "get_pid_list", "process_iter", "get_process_list",
    "avail_phymem", "used_phymem", "total_virtmem", "avail_virtmem",
    "used_virtmem", "cpu_times", "cpu_percent",
    ]

import sys
import os
import time
import signal
import warnings
import errno
try:
    import pwd
except ImportError:
    pwd = None

from psutil.error import Error, NoSuchProcess, AccessDenied

# import the appropriate module for our platform only
if sys.platform.lower().startswith("linux"):
    from psutil._pslinux import *
    __all__.extend(["cached_phymem", "phymem_buffers"])

elif sys.platform.lower().startswith("win32"):
    from psutil._psmswindows import *

elif sys.platform.lower().startswith("darwin"):
    from psutil._psosx import *

elif sys.platform.lower().startswith("freebsd"):
    from psutil._psbsd import *

else:
    raise NotImplementedError('platform %s is not supported' % sys.platform)


class CPUTimes:
    """This class contains information about CPU times.
    It is not used directly but it's returned as an instance by
    psutil.cpu_times() function.

    Every CPU time is accessible in form of an attribute and represents
    the time CPU has spent in the given mode.

    The attributes availability varies depending on the platform.
    Here follows a list of all available attributes:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
    """

    def __init__(self, **kwargs):
        self.__attrs = []
        for name in kwargs:
            setattr(self, name, kwargs[name])
            self.__attrs.append(name)

    def __str__(self):
        string = []
        for attr in self.__attrs:
            value = getattr(self, attr)
            string.append("%s=%s" %(attr, value))
        return '; '.join(string)

    def __iter__(self):
        for attr in self.__attrs:
            yield getattr(self, attr)


class Process(object):
    """Represents an OS process."""

    def __init__(self, pid):
        """Create a new Process object, raises NoSuchProcess if the PID
        does not exist, and ValueError if the parameter is not an
        integer PID."""
        if not isinstance(pid, int):
            raise ValueError("An integer is required")
        if not pid_exists(pid):
            raise NoSuchProcess(pid, None, "no process found with PID %s" % pid)
        self._pid = pid
        # platform-specific modules define an PlatformProcess
        # implementation class
        self._platform_impl = PlatformProcess(pid)
        # try to init CPU times, if it raises AccessDenied then suppress
        # it so it won't interrupt the constructor. First call to
        # get_cpu_percent() will trigger the AccessDenied exception
        # instead.
        try:
            self._last_sys_time = time.time()
            self._last_user_time, self._last_kern_time = self.get_cpu_times()
        except AccessDenied:
            self._last_user_time, self._last_kern_time = None, None

    def __str__(self):
        try:
            pid = self.pid
            name = repr(self.name)
            cmdline = self.cmdline and repr(' '.join(self.cmdline))
        except NoSuchProcess:
            details = "(pid=%s (terminated))" % self.pid
        except AccessDenied:
            details = "(pid=%s)" % (self.pid)
        else:
            if cmdline:
                details = "(pid=%s, name=%s, cmdline=%s)" % (pid, name, cmdline)
            else:
                details = "(pid=%s, name=%s)" % (pid, name)
        return "%s.%s %s" % (self.__class__.__module__,
                             self.__class__.__name__, details)

    def __repr__(self):
        return "<%s at %s>" % (self.__str__(), id(self))

    def __eq__(self, other):
        """Test for equality with another Process object based on pid
        and creation time.
        """
        h1 = (self.pid, self.create_time)
        h2 = (other.pid, other.create_time)
        return h1 == h2

    @property
    def pid(self):
        """The process pid."""
        return self._pid

    @property
    def ppid(self):
        """The process parent pid."""
        return self._platform_impl.get_process_ppid()

    @property
    def parent(self):
        """Return the parent process as a Process object. If no ppid is
        known then return None."""
        if self.ppid is not None:
            return Process(self.ppid)
        return None

    @property
    def name(self):
        """The process name."""
        name = self._platform_impl.get_process_name()
        # On UNIX the name gets truncated to the first 15 characters.
        # If it matches the first part of the cmdline we return that 
        # one instead because it's usually more explicative.
        # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
        if os.name == 'posix':
            cmdline = self.cmdline
            if cmdline:
                extended_name = os.path.basename(cmdline[0])
                if extended_name.startswith(name):
                    return extended_name
        # XXX - needs refactoring
        self._platform_impl._process_name = name
        return name

    @property
    def exe(self):
        """The process executable as an absolute path name."""
        exe = self._platform_impl.get_process_exe()
        # if we have the cmdline but not the exe, figure it out from argv[0]
        if not exe:
            cmdline = self.cmdline
            if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
                _exe = os.path.realpath(cmdline[0])
                if os.path.isfile(_exe) and os.access(_exe, os.X_OK):
                    return _exe
        return exe

    @property
    def path(self):
        msg = "'path' property is deprecated; use 'os.path.dirname(exe)' instead"
        warnings.warn(msg, DeprecationWarning)
        return os.path.dirname(self.exe)

    @property
    def cmdline(self):
        """The command line process has been called with."""
        return self._platform_impl.get_process_cmdline()

    @property
    def uid(self):
        """The real user id of the current process."""<commit_msg>re-set extended_name variable back to _process_impl obj<commit_after>#!/usr/bin/env python
#
# $Id$
#

"""psutil is a module providing convenience functions for managing
processes in a portable way by using Python.
"""

__version__ = "0.2.0"
version_info = tuple([int(num) for num in __version__.split('.')])

__all__ = [
    # exceptions
    "Error", "NoSuchProcess", "AccessDenied",
    # constants
    "NUM_CPUS", "TOTAL_PHYMEM", "version_info", "__version__",
    # classes
    "Process",
    # functions
    "test", "pid_exists", "get_pid_list", "process_iter", "get_process_list",
    "avail_phymem", "used_phymem", "total_virtmem", "avail_virtmem",
    "used_virtmem", "cpu_times", "cpu_percent",
    ]

import sys
import os
import time
import signal
import warnings
import errno
try:
    import pwd
except ImportError:
    pwd = None

from psutil.error import Error, NoSuchProcess, AccessDenied

# import the appropriate module for our platform only
if sys.platform.lower().startswith("linux"):
    from psutil._pslinux import *
    __all__.extend(["cached_phymem", "phymem_buffers"])

elif sys.platform.lower().startswith("win32"):
    from psutil._psmswindows import *

elif sys.platform.lower().startswith("darwin"):
    from psutil._psosx import *

elif sys.platform.lower().startswith("freebsd"):
    from psutil._psbsd import *

else:
    raise NotImplementedError('platform %s is not supported' % sys.platform)


class CPUTimes:
    """This class contains information about CPU times.
    It is not used directly but it's returned as an instance by
    psutil.cpu_times() function.

    Every CPU time is accessible in form of an attribute and represents
    the time CPU has spent in the given mode.

    The attributes availability varies depending on the platform.
    Here follows a list of all available attributes:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
    """

    def __init__(self, **kwargs):
        self.__attrs = []
        for name in kwargs:
            setattr(self, name, kwargs[name])
            self.__attrs.append(name)

    def __str__(self):
        string = []
        for attr in self.__attrs:
            value = getattr(self, attr)
            string.append("%s=%s" %(attr, value))
        return '; '.join(string)

    def __iter__(self):
        for attr in self.__attrs:
            yield getattr(self, attr)


class Process(object):
    """Represents an OS process."""

    def __init__(self, pid):
        """Create a new Process object, raises NoSuchProcess if the PID
        does not exist, and ValueError if the parameter is not an
        integer PID."""
        if not isinstance(pid, int):
            raise ValueError("An integer is required")
        if not pid_exists(pid):
            raise NoSuchProcess(pid, None, "no process found with PID %s" % pid)
        self._pid = pid
        # platform-specific modules define an PlatformProcess
        # implementation class
        self._platform_impl = PlatformProcess(pid)
        # try to init CPU times, if it raises AccessDenied then suppress
        # it so it won't interrupt the constructor. First call to
        # get_cpu_percent() will trigger the AccessDenied exception
        # instead.
        try:
            self._last_sys_time = time.time()
            self._last_user_time, self._last_kern_time = self.get_cpu_times()
        except AccessDenied:
            self._last_user_time, self._last_kern_time = None, None

    def __str__(self):
        try:
            pid = self.pid
            name = repr(self.name)
            cmdline = self.cmdline and repr(' '.join(self.cmdline))
        except NoSuchProcess:
            details = "(pid=%s (terminated))" % self.pid
        except AccessDenied:
            details = "(pid=%s)" % (self.pid)
        else:
            if cmdline:
                details = "(pid=%s, name=%s, cmdline=%s)" % (pid, name, cmdline)
            else:
                details = "(pid=%s, name=%s)" % (pid, name)
        return "%s.%s %s" % (self.__class__.__module__,
                             self.__class__.__name__, details)

    def __repr__(self):
        return "<%s at %s>" % (self.__str__(), id(self))

    def __eq__(self, other):
        """Test for equality with another Process object based on pid
        and creation time.
        """
        h1 = (self.pid, self.create_time)
        h2 = (other.pid, other.create_time)
        return h1 == h2

    @property
    def pid(self):
        """The process pid."""
        return self._pid

    @property
    def ppid(self):
        """The process parent pid."""
        return self._platform_impl.get_process_ppid()

    @property
    def parent(self):
        """Return the parent process as a Process object. If no ppid is
        known then return None."""
        if self.ppid is not None:
            return Process(self.ppid)
        return None

    @property
    def name(self):
        """The process name."""
        name = self._platform_impl.get_process_name()
        if os.name == 'posix':
            # On UNIX the name gets truncated to the first 15 characters.
            # If it matches the first part of the cmdline we return that 
            # one instead because it's usually more explicative.
            # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
            cmdline = self.cmdline
            if cmdline:
                extended_name = os.path.basename(cmdline[0])
                if extended_name.startswith(name):
                    name = extended_name
        # XXX - perhaps needs refactoring
        self._platform_impl._process_name = name
        return name

    @property
    def exe(self):
        """The process executable as an absolute path name."""
        exe = self._platform_impl.get_process_exe()
        # if we have the cmdline but not the exe, figure it out from argv[0]
        if not exe:
            cmdline = self.cmdline
            if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
                _exe = os.path.realpath(cmdline[0])
                if os.path.isfile(_exe) and os.access(_exe, os.X_OK):
                    return _exe
        return exe

    @property
    def path(self):
        msg = "'path' property is deprecated; use 'os.path.dirname(exe)' instead"
        warnings.warn(msg, DeprecationWarning)
        return os.path.dirname(self.exe)

    @property
    def cmdline(self):
        """The command line process has been called with."""
        return self._platform_impl.get_process_cmdline()

    @property
    def uid(self):
        """The real user id of the current process."""
{'fraction_non_alphanumeric': 0.10366036603660365, 'fraction_numerical': 0.0021002100210021, 'mean_word_length': 2.3018821198613173, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1633322', 'n_tokens_mistral': 3900, 'n_tokens_neox': 3803, 'n_words': 1216}