本文整理汇总了Python中win32com.client.Dispatch方法的典型用法代码示例。如果您正苦于以下问题:Python client.Dispatch方法的具体用法?Python client.Dispatch怎么用?Python client.Dispatch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类win32com.client
的用法示例。
在下文中一共展示了client.Dispatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestObjectFromWindow
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def TestObjectFromWindow():
# Check we can use ObjectFromLresult to get the COM object from the
# HWND - see KB Q249232
# Locating the HWND is different than the KB says...
hwnd = win32gui.FindWindow('IEFrame', None)
for child_class in ['TabWindowClass', 'Shell DocObject View',
'Internet Explorer_Server']:
hwnd = win32gui.FindWindowEx(hwnd, 0, child_class, None)
assert hwnd, "Couldn't find '%s'" % (child_class,)
# But here is the point - once you have an 'Internet Explorer_Server',
# you can send a message and use ObjectFromLresult to get it back.
msg = win32gui.RegisterWindowMessage("WM_HTML_GETOBJECT")
rc, result = win32gui.SendMessageTimeout(hwnd, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0)
doc = Dispatch(ob)
# just to prove it works, set the background color of the document.
for color in "red green blue orange white".split():
doc.bgColor = color
time.sleep(0.2)
示例2: test_shortcut
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def test_shortcut(self):
"""Verifies the shortcut is created and links properly."""
shortcut_path = os.path.join(self.log_dir, self.testbed_name,
'latest.lnk')
shell = client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(shortcut_path)
self.assertFalse(shortcut.Targetpath)
mock_test_config = self.create_mock_test_config(
self.base_mock_test_config)
tr = test_runner.TestRunner(self.log_dir, self.testbed_name)
with tr.mobly_logger():
pass
shortcut = shell.CreateShortCut(shortcut_path)
# Normalize paths for case and truncation
normalized_shortcut_path = os.path.normcase(
win32file.GetLongPathName(shortcut.Targetpath))
normalized_logger_path = os.path.normcase(
win32file.GetLongPathName(logging.log_path))
self.assertEqual(normalized_shortcut_path, normalized_logger_path)
示例3: create_alias
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def create_alias(target_path, alias_path):
"""Creates an alias at 'alias_path' pointing to the file 'target_path'.
On Unix, this is implemented via symlink. On Windows, this is done by
creating a Windows shortcut file.
Args:
target_path: Destination path that the alias should point to.
alias_path: Path at which to create the new alias.
"""
if platform.system() == 'Windows' and not alias_path.endswith('.lnk'):
alias_path += '.lnk'
if os.path.lexists(alias_path):
os.remove(alias_path)
if platform.system() == 'Windows':
from win32com import client
shell = client.Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(alias_path)
shortcut.Targetpath = target_path
shortcut.save()
else:
os.symlink(target_path, alias_path)
示例4: set_automatic_updates
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def set_automatic_updates(enabled):
# TODO(alexpilotti): the following settings are ignored on
# Windows 10 / Windows Server 2016 build 14393
auto_update = client.Dispatch("Microsoft.Update.AutoUpdate")
if enabled:
auto_update.Settings.NotificationLevel = AU_SCHEDULED_INSTALLATION
osutils = osutils_factory.get_os_utils()
if not osutils.check_os_version(6, 2):
# NOTE(alexpilotti): this setting is not supported starting
# with Windows 8 / Windows Server 2012
hour = random.randint(MIN_INSTALL_HOUR, MAX_INSTALL_HOUR)
auto_update.SettingsScheduledInstallationTime = hour
else:
auto_update.Settings.NotificationLevel = AU_DISABLED
auto_update.Settings.Save()
示例5: __init__
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def __init__(self,xlsFile="", Visible=1):
self.xlApp = Dispatch("Excel.Application")
self.xlApp.Visible = Visible
xlChart.numWkBooks = xlChart.numWkBooks + 1
# I don't think the sheet and column lists should be mapped
# (unfortunately, they are right now)
self.sheetList = []
self.chartList = []
self.chartNColumns = []
self.chartNRows = []
self.leaveOpen = 1
self.nRows = 0
self.nColumns = 0
self.formula = xlChFormula.xlChFormula() # a scratch variable
if len(xlsFile)>0: # opening an existing XLS file
xlsFile = os.path.abspath(xlsFile) # Excel likes absolute path names
self.xlApp.Workbooks.Open(xlsFile)
self.initFromXLSFile()
self.xlBook = None
else: # making a new XLS file
self.xlBook = self.xlApp.Workbooks.Add()
self.xlSheet = self.xlApp.Sheets(1)
self.sheetList.append( self.xlSheet )
示例6: make_app
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def make_app(self):
with open("traffic.bat", "w") as fh:
fh.write(self.windows_batch.format(sys.executable))
try:
from win32com.client import Dispatch
except ImportError:
subprocess.call("conda install pywin32")
print("Missing package installed, relaunch script")
return
path = "traffic.lnk"
target = str(Path("traffic.bat").absolute())
icon_path = ICON_PATH / "travel.ico"
shell = Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.TargetPath = target
shortcut.IconLocation = icon_path.as_posix()
shortcut.save()
示例7: __start__
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def __start__(self):
try:
self.comObj = GetActiveObject(YARD_CLSID)
except com_error:
self.StartYardServer()
try:
self.comObj = GetActiveObject(YARD_CLSID)
except:
raise
if self.comObj:
self.comObj = Dispatch(YARD_CLSID)
class SubEventHandler(EventHandler):
plugin = self
TriggerEvent = self.TriggerEvent
self.workerThread = YardWorkerThread(self, SubEventHandler)
try:
self.workerThread.Start( 60.0 )
except:
self.workerThread = None
raise self.Exception( self.text.errorMesg )
self.isEnabled = True
示例8: __start__
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def __start__(self, hostname, username, password):
self.hsi = Dispatch("HomeSeer2.application")
self.connected = False
self.hostname = hostname
self.username = username
self.password = password
print "Trying to connect to Homeseer-host " + self.hostname + " using user " + self.username + "."
self.hsi.SetHost(self.hostname)
rval = self.hsi.Connect(self.username, self.password)
if rval == "":
print "Successfully connected to Homeseer " + self.hostname + " using user " + self.username + "."
self.connected = True
else:
print "Error: " + rval
self.hsi.Disconnect
self.connected = False
if self.connected:
self.hs = Dispatch("homeseer.application")
示例9: get_connection
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def get_connection(self):
"""
Create a new WMI connection
"""
self.logger.debug(
u"Connecting to WMI server (host=%s, namespace=%s, provider=%s, username=%s).",
self.host,
self.namespace,
self.provider,
self.username,
)
additional_args = []
if self.provider != ProviderArchitecture.DEFAULT:
context = Dispatch("WbemScripting.SWbemNamedValueSet")
context.Add("__ProviderArchitecture", self.provider)
additional_args = [None, "", 128, context]
locator = Dispatch("WbemScripting.SWbemLocator")
connection = locator.ConnectServer(self.host, self.namespace, self.username, self.password, *additional_args)
return connection
示例10: addToTaskbar
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def addToTaskbar(file_path, dir_path, name):
you = os.getlogin()
startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
'Microsoft', 'Internet Explorer', 'Quick Launch',
'User Pinned', 'TaskBar')
name = name + '.lnk'
path = os.path.join(startup, name)
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = file_path
shortcut.WorkingDirectory = dir_path
shortcut.IconLocation = file_path
shortcut.save()
示例11: make_shortcut
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def make_shortcut(file_path, dir_path, name):
you = os.getlogin()
startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
'Microsoft', 'Windows', 'SendTo')
name = name + '.lnk'
path = os.path.join(startup, name)
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = file_path
shortcut.WorkingDirectory = dir_path
shortcut.IconLocation = file_path
shortcut.save()
示例12: make_shortcut
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def make_shortcut(file_path, dir_path, name):
you = os.getlogin()
startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
name = name + '.lnk'
path = os.path.join(startup, name)
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = file_path
shortcut.WorkingDirectory = dir_path
shortcut.IconLocation = file_path
shortcut.save()
示例13: doc_to_docx
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def doc_to_docx(doc_path, docx_path):
"""将doc文件转为docx文件
:param doc_path: doc文件夹的路径
:param docx_path: 保存docx文件夹的路径
"""
from win32com import client
w = client.Dispatch('Word.Application')
doc = w.Documents.Open(doc_path)
doc.SaveAs(docx_path, 16) # 必须有参数16,否则会出错.
w.Quit()
示例14: ScpCreate
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def ScpCreate(
service_binding_info,
service_class_name, # Service class string to store in SCP.
account_name = None, # Logon account that needs access to SCP.
container_name = None,
keywords = None,
object_class = "serviceConnectionPoint",
dns_name_type = "A",
dn = None,
dns_name = None,
):
container_name = container_name or service_class_name
if not dns_name:
# Get the DNS name of the local computer
dns_name = win32api.GetComputerNameEx(win32con.ComputerNameDnsFullyQualified)
# Get the distinguished name of the computer object for the local computer
if dn is None:
dn = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN)
# Compose the ADSpath and bind to the computer object for the local computer
comp = adsi.ADsGetObject("LDAP://" + dn, adsi.IID_IDirectoryObject)
# Publish the SCP as a child of the computer object
keywords = keywords or []
# Fill in the attribute values to be stored in the SCP.
attrs = [
("cn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (container_name,)),
("objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (object_class,)),
("keywords", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, keywords),
("serviceDnsName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name,)),
("serviceDnsNameType", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name_type,)),
("serviceClassName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_class_name,)),
("serviceBindingInformation", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_binding_info,)),
]
new = comp.CreateDSObject("cn=" + container_name, attrs)
logger.info("New connection point is at %s", container_name)
# Wrap in a usable IDispatch object.
new = Dispatch(new)
# And allow access to the SCP for the specified account name
AllowAccessToScpProperties(account_name, new)
return new
示例15: _dynamic_
# 需要导入模块: from win32com import client [as 别名]
# 或者: from win32com.client import Dispatch [as 别名]
def _dynamic_(self, name, lcid, wFlags, args):
# Ensure any newly added items are available.
self.engine.RegisterNewNamedItems()
self.engine.ProcessNewNamedItemsConnections()
if wFlags & pythoncom.INVOKE_FUNC:
# attempt to call a function
try:
func = getattr(self.scriptNamespace, name)
if not _is_callable(func):
raise AttributeError(name) # Not a function.
realArgs = []
for arg in args:
if type(arg)==PyIDispatchType:
realArgs.append(Dispatch(arg))
else:
realArgs.append(arg)
try:
# xxx - todo - work out what code block to pass???
return self.engine.ApplyInScriptedSection(None, func, tuple(realArgs))
except COMException, (hr, msg, exc, arg):
raise
except AttributeError:
if not wFlags & pythoncom.DISPATCH_PROPERTYGET:
raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
if wFlags & pythoncom.DISPATCH_PROPERTYGET:
# attempt to get a property
try:
ret = getattr(self.scriptNamespace, name)
if _is_callable(ret):
raise AttributeError(name) # Not a property.
except AttributeError:
raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
except COMException, instance:
raise
except: