예제 #1
0
 def GetSubList(self):
     return [
         HLIHeadingCategory(),
         HLI_IEnumMoniker(pythoncom.GetRunningObjectTable().EnumRunning(),
                          "Running Objects"),
         HLIHeadingRegisterdTypeLibs()
     ]
예제 #2
0
    def __init__(self, hwnd=None):
        '''
        If hwnd is None, current window will be retrieved
        '''
        DefaultApplication.__init__(self, hwnd)
        if hwnd:
            pids = process.GetWindowThreadProcessId(hwnd)
        else:
            pids = None

        self.dte = None
        ctx = pythoncom.CreateBindCtx()
        rot = pythoncom.GetRunningObjectTable()
        for mk in rot:
            name = mk.GetDisplayName(ctx, None)
            if name.find('VisualStudio.DTE') < 0:
                continue

            if not pids:
                obj = rot.GetObject(mk)
                interface = obj.QueryInterface(pythoncom.IID_IDispatch)
                self.dte = com.client.Dispatch(interface)
                break

            pos = name.rfind(':')
            if pos < 0:
                continue
            name = name[pos + 1:]
            val = int(name)
            if val in pids:
                obj = rot.GetObject(mk)
                interface = obj.QueryInterface(pythoncom.IID_IDispatch)
                self.dte = com.client.Dispatch(interface)
                break
예제 #3
0
def printrunningcoms():
    """Print active COM objects"""
    context = pythoncom.CreateBindCtx(0)
    running_coms = pythoncom.GetRunningObjectTable()
    monikers = running_coms.EnumRunning()
    for moniker in monikers:
        print('-' * 100)
        print(moniker.GetDisplayName(context, moniker))
        print(moniker.Hash())
def _get_dte_from_pid(pid=0):
    """プロセスIDからDTEを検索する。

    pid=None    起動しているVisualStudioを全て返す
    pid!=None   pidからVisualStudioを検索して返す、見つからなければNoneを返す。

    todo:ソリューションのファイル名から探す関数を追加する。
    """
    rot = pythoncom.GetRunningObjectTable()
    try:
        lst_dte = []
        rot_enum = rot.EnumRunning()

        while 1:
            monikers = rot_enum.Next()
            if not monikers:
                break

            display_name = monikers[0].GetDisplayName(
                pythoncom.CreateBindCtx(0), None)
            if display_name.startswith('!VisualStudio.DTE'):
                dte_pid = 0
                pos = display_name.rfind(':')
                if 0 <= pos:
                    try:
                        dte_pid = int(display_name[pos + 1:])
                    except ValueError:
                        dte_pid = 0

                if pid and (pid != dte_pid):
                    continue

                obj = rot.GetObject(monikers[0])
                if 1:
                    interface = obj.QueryInterface(pythoncom.IID_IDispatch)
                    dte = win32com.client.Dispatch(interface)
                else:
                    dte = win32com.client.Dispatch("VisualStudio.DTE")

                Solution = _dte_prop(dte, "Solution")
                dte_sln = unicode(_dte_prop(Solution, "FullName"))

                if None is dte_pid:
                    dte_pid = 0

                if None is dte_sln:
                    dte_sln = ""

                lst_dte.append((
                    dte,
                    dte_pid,
                    dte_sln,
                ))
        return lst_dte
    finally:
        rot = None
예제 #5
0
파일: com_utils.py 프로젝트: zyxws012/PTVS
def enum_running_monikers():
    try:
        r = pythoncom.GetRunningObjectTable()
        for moniker in r:
            yield moniker
    except com_error as e:
        if e.args[0] == winerror.E_ACCESSDENIED:
            raise Exception(
                "Access to the running object table was denied. This may be due to a high-privilege registered object"
            )
예제 #6
0
def is_file_open(fullname):
    """
    Checks the Running Object Table (ROT) for the fully qualified filename
    """
    context = pythoncom.CreateBindCtx()
    for moniker in pythoncom.GetRunningObjectTable():
        name = moniker.GetDisplayName(context, None)
        if name.lower() == fullname.lower():
            return True
    return False
예제 #7
0
def dispatch_running(disp_names):
    "Dispatch object in ROT"
    if not isinstance(disp_names, (list, tuple)):
        disp_names = (disp_names, )
    context = pythoncom.CreateBindCtx(0)
    rot = pythoncom.GetRunningObjectTable()
    for i in rot:
        dp = i.GetDisplayName(context, None)
        if dp in disp_names:
            obj = rot.GetObject(i).QueryInterface(pythoncom.IID_IDispatch)
            print("Found running object", dp)
            return w32client.Dispatch(obj)
예제 #8
0
def is_file_open(fullname):
    """
    Checks the Running Object Table (ROT) for the fully qualified filename
    """
    if not PY3:
        if isinstance(fullname, str):
            fullname = unicode(fullname, 'utf-8')
    context = pythoncom.CreateBindCtx()
    for moniker in pythoncom.GetRunningObjectTable():
        name = moniker.GetDisplayName(context, None)
        if name.lower() == fullname.lower():
            return True
    return False
예제 #9
0
파일: com_utils.py 프로젝트: zyxws012/PTVS
def get_running_xlWorkbook_for_filename(filename):
    # If we
    wbPartialMatch = None
    filename = filename.lower()
    context = pythoncom.CreateBindCtx(0)
    for moniker in enum_running_monikers():
        name = moniker.GetDisplayName(context, None).lower()
        # name will be either a temp name "book1" or a full filename  "c:\temp\fob.xlsx"
        # use moniker.GetClassID() to narrow it down to a file Monikor?
        # match on full path, case insensitive
        if (filename == name):
            obj = pythoncom.GetRunningObjectTable().GetObject(moniker)
            wb = win32.Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch))
            return wb
        # check for a partial match
        if name.endswith('\\' + filename):
            obj = pythoncom.GetRunningObjectTable().GetObject(moniker)
            wbPartialMatch = win32.Dispatch(
                obj.QueryInterface(pythoncom.IID_IDispatch))

    # Didn't find a full match. Return partial match if we found one.
    return wbPartialMatch
예제 #10
0
 def testit(self):
     ctx = pythoncom.CreateBindCtx()
     rot = pythoncom.GetRunningObjectTable()
     num = 0
     for mk in rot:
         name = mk.GetDisplayName(ctx, None)
         num += 1
         # Monikers themselves can iterate their contents (sometimes :)
         try:
             for sub in mk:
                 num += 1
         except pythoncom.com_error as exc:
             if exc.hresult != winerror.E_NOTIMPL:
                 raise
예제 #11
0
def getOpenedFileObject(name):
    if name in comobj_cache:
        try:
            #http://stackoverflow.com/questions/3500503/check-com-interface-still-alive
            o = comobj_cache[name]
            o._oleobj_.GetTypeInfoCount()
            return o
        except:
            del comobj_cache[name]
    ctx, rot = pythoncom.CreateBindCtx(0), pythoncom.GetRunningObjectTable()
    for i in rot:
        if i.GetDisplayName(ctx, None) == name:
            comobj_cache[name] = gencache.EnsureDispatch(
                rot.GetObject(i).QueryInterface(pythoncom.IID_IDispatch))
            return comobj_cache[name]
예제 #12
0
파일: com_utils.py 프로젝트: zyxws012/PTVS
def get_open_xlWorkbooks():
    IID_Workbook = pythoncom.pywintypes.IID(
        "{000208DA-0000-0000-C000-000000000046}")
    l = []
    for moniker in enum_running_monikers():
        obj = pythoncom.GetRunningObjectTable().GetObject(moniker)
        try:
            wb = win32.Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch))
            # Python COM doesn't support QI for arbitrary interfaces, so we can't
            # just QI for IID_Workbook({000208DA-0000-0000-C000-000000000046})
            if (getattr(wb, "CLSID", None) == IID_Workbook):
                l.append(wb)
        except com_error:
            pass
    return l
예제 #13
0
def _get_dte_from_rot(pid=None, sln=None):
    '''Returns single dte if pid or sln is passed.
    Otherwise returns a list of (dte, pid, sln) tuples.'''
    import pythoncom
    try:
        lst_dte = []
        rot = pythoncom.GetRunningObjectTable()
        rot_enum = rot.EnumRunning()
        while 1:
            monikers = rot_enum.Next()
            if not monikers:
                break
            ctx = pythoncom.CreateBindCtx(0)
            display_name = monikers[0].GetDisplayName(ctx, None)
            if display_name.startswith('!VisualStudio.DTE'):
                logging.info('_get_dte_from_rot display_name: >%s<' %
                             display_name)
                dte_pid = 0
                pos = display_name.rfind(':')
                if pos >= 0:
                    try:
                        dte_pid = int(display_name[pos + 1:])
                    except ValueError:
                        dte_pid = 0
                if pid and pid != dte_pid:
                    continue
                obj = rot.GetObject(monikers[0])
                interface = obj.QueryInterface(pythoncom.IID_IDispatch)
                import win32com.client
                dte = win32com.client.Dispatch(interface)
                if pid:
                    logging.info(
                        '_get_dte_from_rot returning dte for pid: %s' %
                        (pid, ))
                    return dte
                dte_sln = str(dte.Solution.FullName)
                if sln and dte_sln.endswith(sln):
                    return dte
                if not dte_sln:
                    dte_sln = '(pid: %s - no open solution)' % (dte_pid, )
                lst_dte.append((
                    dte,
                    dte_pid,
                    dte_sln,
                ))
        return lst_dte
    finally:
        rot = None
예제 #14
0
    def connect_to_session(self, explicit_wait=0):
        """Connects to an open session SAP.

        See `Opening a connection / Before running tests` for details about requirements before connecting to a session.

        Optionally `set explicit wait` can be used to set the explicit wait time.

        *Examples*:
        | *Keyword*             | *Attributes*          |
        | connect to session    |                       |
        | connect to session    | 3                     |
        | connect to session    | explicit_wait=500ms   |

        """
        lenstr = len("SAPGUI")
        if threading.currentThread().getName() != 'MainThread':
            pythoncom.CoInitialize()
        rot = pythoncom.GetRunningObjectTable()
        rotenum = rot.EnumRunning()
        while True:
            monikers = rotenum.Next()
            if not monikers:
                break
            ctx = pythoncom.CreateBindCtx(0)
            name = monikers[0].GetDisplayName(ctx, None)

            if name[-lenstr:] == "SAPGUI":
                obj = rot.GetObject(monikers[0])
                sapgui = win32com.client.Dispatch(
                    obj.QueryInterface(pythoncom.IID_IDispatch))
                self.sapapp = sapgui.GetScriptingEngine
                # Set explicit_wait after connection succeed
                self.set_explicit_wait(explicit_wait)

        if hasattr(self.sapapp, "OpenConnection") == False:
            self.take_screenshot()
            message = "Could not connect to Session, is Sap Logon Pad open?"
            raise Warning(message)
        # run explicit wait last
        time.sleep(self.explicit_wait)
예제 #15
0
def get_xl_app(parent=None):
    """
    Return an Excel Application instance.

    Unlike using win32com.client.Dispatch("Excel.Application") the
    Application returned will always be the one that corresponds
    to the parent process.
    """
    # Get the window handle set by the parent process
    parent_hwnd = os.environ["PYXLL_EXCEL_HWND"]

    # Iterate over the running object table looking for the Excel Workbook
    # object from the parent process' Application object.
    context = pythoncom.CreateBindCtx(0)
    for moniker in pythoncom.GetRunningObjectTable():
        try:
            # Workbook implements IOleWindow so only consider objects implementing that
            window = moniker.BindToObject(context, None, pythoncom.IID_IOleWindow)
            disp = window.QueryInterface(pythoncom.IID_IDispatch)

            # Get a win32com Dispatch object from the PyIDispatch object as it's
            # easier to work with.
            obj = win32com.client.Dispatch(disp)

        except pythoncom.com_error:
            # Skip any objects we're not interested in
            continue

        # Check the object we've found is a Workbook
        if getattr(obj, "CLSID", None) == IID_Workbook:
            # Get the Application from the Workbook and if its window matches return it.
            xl_app = obj.Application
            if str(xl_app.Hwnd) == parent_hwnd:
                return xl_app

    # This can happen if the parent process has terminated without terminating
    # the child process.
    raise RuntimeError("Parent Excel application not found")
예제 #16
0
def df_to_csv(df,path):
    """Writes dataframe to .csv, first closing the .csv if it's open elsewhere."""
    # tries to save a df to a csv file,
    # traps io error and if the file is open elsewhere, closes the file
    # Adapted from
    # http: // timgolden.me.uk / python / win32_how_do_i / see - if -an - excel - workbook - is -open.html

    if sys.platform != 'win32' and sys.platform != 'win64':
        df.to_csv(path)
    else:

        try:
            df.to_csv(path)
            logging.info('saved to %s', path)
            pass
        except IOError:
            context = pythoncom.CreateBindCtx(0)
            for moniker in pythoncom.GetRunningObjectTable():
                name = moniker.GetDisplayName(context, None)
                if name == path:
                    obj = win32com.client.GetObject(path)
                    obj.Close(True)
            df.to_csv(path)
예제 #17
0
def _get_excel_running_workbook(workbook_name):
    lenstr = len(workbook_name)
    obj = None
    rot = pythoncom.GetRunningObjectTable()
    rotenum = rot.EnumRunning()

    while True:
        monikers = rotenum.Next()
        if not monikers: break

        ctx = pythoncom.CreateBindCtx(0)
        name = monikers[0].GetDisplayName(ctx, None)

        if name[-lenstr:] == workbook_name:
            obj = rot.GetObject(monikers[0])


    if obj is None:
        raise NoExcelWorkbookException(f'Could not find open workbook {workbook_name}')

    workbook = win32com.client.gencache.EnsureDispatch(obj.QueryInterface(pythoncom.IID_IDispatch))

    return workbook.Application
예제 #18
0
def spread_iterator():
    for moniker in pythoncom.GetRunningObjectTable():
        try:
            # Workbook implements IOleWindow so only consider objects implementing that
            window = moniker.BindToObject(pythoncom.CreateBindCtx(0), None,
                                          pythoncom.IID_IOleWindow)
            disp = window.QueryInterface(pythoncom.IID_IDispatch)

            # Get a win32com Dispatch object from the PyIDispatch object as it's
            # easier to work with.
            book = win32com.client.Dispatch(disp)

        except pythoncom.com_error:
            # Skip any objects we're not interested in
            continue

        try:
            book.Sheets(1)  #Object is a book with sheets
        except:
            continue

        bookname = moniker.GetDisplayName(pythoncom.CreateBindCtx(0), None)

        yield bookname, book
예제 #19
0
 def _get_open_file(self, filepath):
     context = pythoncom.CreateBindCtx(0)
     for moniker in pythoncom.GetRunningObjectTable():
         if filepath == os.path.abspath(
                 moniker.GetDisplayName(context, None)):
             return win32com.client.GetObject(filepath)
예제 #20
0
import os
import pythoncom
import win32api
import win32com.client

# Jamais reussi a lui faire afficher quoique ce soit et pourtant ca devrait.
context = pythoncom.CreateBindCtx(0)
print("Starting")
for moniker in pythoncom.GetRunningObjectTable():
    print("OK")
    name = moniker.GetDisplayName(context, None)
    print(name)
print("Finished")
예제 #21
0
파일: _comutils.py 프로젝트: fellobos/ltapy
 def __init__(self):
     self.rot = pythoncom.GetRunningObjectTable()