我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用win32api.ShellExecute()。
def install_service(): import win32api import time if not os.path.exists(zabbix_install_log): log.info('Install zabbix service') try: win32api.ShellExecute(0, 'runas', zabbix_agent_bin_file, '--config %s --install' % zabbix_agent_conf_file, '', 0) time.sleep(2) # it is not essential log.info('Install zabbix service finished') with open(zabbix_install_log, 'w') as f: f.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + ' service installed.') except Exception as e: print e for item in list(e): if isinstance(item, str): print item.decode(DEFAULT_LOCALE_ENCODING), else: print item, log.error('Install zabbix service failed') raise RuntimeError
def toolbar_icon_clicked(self, widget, movie): if not movie or not movie.trailer: return False use_shell = True command = self.get_config_value('command', self.preferences['command']['default']) if is_windows_system(): use_shell = False # Popen with shell=True doesn't work under windows with spaces in filenames if not command: import win32api log.debug('try ShellExecute with trailer %s' % movie.trailer) win32api.ShellExecute(0, None, movie.trailer, None, None, 0) return if '{1}' in command: command = command.replace('{1}', movie.trailer) else: # make a sequence results in Popen calls list2cmdline command = [command, movie.trailer] log.debug(command) Popen(command, shell=use_shell)
def open_txt(): #????????????test.txt?? path = os.path.abspath('.') file_path = os.path.join(path, 'test.txt') win32api.ShellExecute(0, 'open', file_path, '', '', 1)
def run_service(): import win32api import time import win32service START_PENDING = win32service.SERVICE_START_PENDING or 2 RUNNING = win32service.SERVICE_RUNNING or 4 service_status = check_service_status(ZABBIX_WIN32_SERVICE_NAME) if service_status != START_PENDING or service_status != RUNNING: log.info('Start Zabbix Agent Service') try: win32api.ShellExecute(0, 'runas', 'sc', 'start \"%s\"' % ZABBIX_WIN32_SERVICE_NAME, '', 1) time.sleep(2) # it is not essential log.info('Zabbix Agent service started') except Exception as e: print e for item in list(e): if isinstance(item, str): print item.decode(DEFAULT_LOCALE_ENCODING), else: print item, raise RuntimeError else: log.info('Zabbix Agent service has already started, nothing to do')
def printWindows(pdf, impresora) : ImpresoraPorDefecto = str(win32print.GetDefaultPrinter()) # primero guardamos la impresora por defecto win32print.SetDefaultPrinter(impresora) # luego se cambia la impresora por defecto por la impresora específica win32api.ShellExecute(0, "print", pdf, None, ".", 0) sleep(5) # se espera un tiempo para que se envíe el archivo a la impresora win32print.SetDefaultPrinter(ImpresoraPorDefecto) # vuelve a estar la impresora por defecto original return 0
def OnButHomePage(self, id, code): if code == win32con.BN_CLICKED: win32api.ShellExecute(0, "open", "http://starship.python.net/crew/mhammond/win32", None, "", 1)
def OpenHelpFile(fileName, helpCmd = None, helpArg = None): "Open a help file, given a full path" # default help arg. win32ui.DoWaitCursor(1) try: if helpCmd is None: helpCmd = win32con.HELP_CONTENTS ext = os.path.splitext(fileName)[1].lower() if ext == ".hlp": win32api.WinHelp( win32ui.GetMainFrame().GetSafeHwnd(), fileName, helpCmd, helpArg) # XXX - using the htmlhelp API wreaks havoc with keyboard shortcuts # so we disable it, forcing ShellExecute, which works fine (but # doesn't close the help file when Pythonwin is closed. # Tom Heller also points out http://www.microsoft.com/mind/0499/faq/faq0499.asp, # which may or may not be related. elif 0 and ext == ".chm": import win32help global htmlhelp_handle helpCmd = html_help_command_translators.get(helpCmd, helpCmd) #frame = win32ui.GetMainFrame().GetSafeHwnd() frame = 0 # Dont want it overlapping ours! if htmlhelp_handle is None: htmlhelp_hwnd, htmlhelp_handle = win32help.HtmlHelp(frame, None, win32help.HH_INITIALIZE) win32help.HtmlHelp(frame, fileName, helpCmd, helpArg) else: # Hope that the extension is registered, and we know what to do! win32api.ShellExecute(0, "open", fileName, None, "", win32con.SW_SHOW) return fileName finally: win32ui.DoWaitCursor(-1)
def NeedApp(): import win32ui rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO) if rc==win32con.IDYES: try: parent = win32ui.GetMainFrame().GetSafeHwnd() win32api.ShellExecute(parent, None, 'pythonwin.exe', '/app "%s"' % sys.argv[0], None, 1) except win32api.error, details: win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
def NeedApp(): import win32ui rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO) if rc==win32con.IDYES: try: parent = win32ui.GetMainFrame().GetSafeHwnd() win32api.ShellExecute(parent, None, 'pythonwin.exe', '/app "%s"' % sys.argv[0], None, 1) except win32api.error as details: win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
def open_waveQoE(self): #open waveQoE,wait for 3 seconds try: win32api.ShellExecute(0,'open',WAVEQOE_EXE_PATH,'','',1) print "open waveQoE" time.sleep(3) except: print 'open waveQoE error' log_public(ERR_NO_0005) self.m_ERROR_MSG = ERR_NO_0005 return False #find handle for the waveQoE window hwnd2 = win32gui.FindWindow(WAVEQOE_CLASS,'IxVeriwave WaveQoE Main Page') print 'hwnd2',hwnd2 #move window of 'IxVeriwave WaveQoE Main Page' to top left corner win32gui.MoveWindow(hwnd2,0,0,626,270,1) time.sleep(0.5) #click button -- 'wired and wireless testing' self.myobj.Mouse_LB_D(str_app = WAVEQOE_CLASS,lb_dx = '238',lb_dy = '165',Flag = '1') time.sleep(0.5) #click button -- 'wired only testing' #self.myobj.Mouse_LB_D(str_app='QWidget',lb_dx='426',lb_dy='166',Flag='1') #click button -- 'apply' self.myobj.Mouse_LB_D(str_app = WAVEQOE_CLASS,lb_dx = '305',lb_dy = '240',Flag = '1') return True #----------------------------------------------------------------------------- # Name: choose_conf_file # purpose: choose config file which has saved config infomation for test. # explain: # Author: gongke # # Created: 2013/05/20 #-----------------------------------------------------------------------------
def open_waveApps(self): #open waveApps,wait for 3 seconds try: win32api.ShellExecute(0,'open',WAVEApps_EXE_PATH,'','',1) print "open waveApps" time.sleep(3) except: print 'open waveApps error' log_public(ERR_NO_0005) self.m_ERROR_MSG = ERR_NO_0005 return False ''' #find handle for the waveApps window hwnd2 = win32gui.FindWindow(WAVEApps_CLASS,'IxVeriwave WaveApps Main Page') print 'hwnd2',hwnd2 #move window of 'IxVeriwave WaveApps Main Page' to top left corner win32gui.MoveWindow(hwnd2,0,0,626,270,1) time.sleep(0.5) #click button -- 'wired and wireless testing' self.myobj.Mouse_LB_D(str_app = WAVEApps_CLASS,lb_dx = '238',lb_dy = '165',Flag = '1') time.sleep(0.5) #click button -- 'wired only testing' #self.myobj.Mouse_LB_D(str_app='QWidget',lb_dx='426',lb_dy='166',Flag='1') #click button -- 'apply' self.myobj.Mouse_LB_D(str_app = WAVEApps_CLASS,lb_dx = '305',lb_dy = '240',Flag = '1') ''' return True #----------------------------------------------------------------------------- # Name: choose_conf_file # purpose: choose config file which has saved config infomation for test. # explain: # Author: gongke # # Created: 2013/05/20 #-----------------------------------------------------------------------------
def runAsAdmin(cmdLine=None, wait=True): if os.name != 'nt': raise RuntimeError, "This function is only implemented on Windows." import win32api import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon python_exe = sys.executable if cmdLine is None: cmdLine = [python_exe] + sys.argv elif type(cmdLine) not in (types.TupleType, types.ListType): raise ValueError, "cmdLine is not a sequence." cmd = '"%s"' % (cmdLine[0],) # XXX TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) cmdDir = '' #showCmd = win32con.SW_SHOWNORMAL showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # print "Running", cmd, params # ShellExecute() doesn't seem to allow us to fetch the PID or handle # of the process, so we can't get anything useful from it. Therefore # the more complex ShellExecuteEx() must be used. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) # print "Process handle %s returned code %s" % (procHandle, rc) else: rc = None return rc
def runAsAdmin(cmdLine=None, wait=True): if os.name != 'nt': raise RuntimeError, "This function is only implemented on Windows." import win32api, win32con, win32event, win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon python_exe = sys.executable if cmdLine is None: cmdLine = [python_exe] + sys.argv elif type(cmdLine) not in (types.TupleType,types.ListType): raise ValueError, "cmdLine is not a sequence." cmd = '"%s"' % (cmdLine[0],) # XXX TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL #showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # print "Running", cmd, params # ShellExecute() doesn't seem to allow us to fetch the PID or handle # of the process, so we can't get anything useful from it. Therefore # the more complex ShellExecuteEx() must be used. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) #print "Process handle %s returned code %s" % (procHandle, rc) else: rc = None return rc