Python win32api.ShellExecute() Examples

The following are 17 code examples of win32api.ShellExecute(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32api , or try the search function .
Example #1
Source File: platform.py    From BitTorrent with GNU General Public License v3.0 8 votes vote down vote up
def spawn(*args):
    if os.name == 'nt':
        # do proper argument quoting since exec/spawn on Windows doesn't
        bargs = args
        args = []
        for a in bargs:
            if not a.startswith("/"):
                a.replace('"', '\"')
                a = '"%s"' % a
            args.append(a)

        argstr = ' '.join(args[1:])
        # use ShellExecute instead of spawn*() because we don't want
        # handles (like the controlsocket) to be duplicated
        win32api.ShellExecute(0, "open", args[0], argstr, None, 1) # 1 == SW_SHOW
    else:
        if os.access(args[0], os.X_OK):
            forkback = os.fork()
            if forkback == 0:
                # BUG: stop IPC!
                print "execl ", args[0], args
                os.execl(args[0], *args)
        else:
            #BUG: what should we do here?
            pass 
Example #2
Source File: admin.py    From uac-a-mola with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def RunEmailClient(text):
    """Get the path of default email client through querying the
        Windows registry. """
    try:
        em_reg = _winreg.OpenKey(
            _winreg.HKEY_CLASSES_ROOT,
            "\\mailto\\shell\\open\\command"
        )
        EmPath = _winreg.EnumValue(em_reg,0)[1]
        _winreg.CloseKey(em_reg)
        EmPath = EmPath.split('"')[1]
    except:
        eg.PrintError(text.error9)
    else:
        head, tail = os.path.split(EmPath)
        win32api.ShellExecute(
            0,
            None,
            tail,
            None,
            head,
            1
        )
#=============================================================================== 
Example #4
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self):
        if self.plugin.useRunCmdPlugin:
            command = self.value[1]
        else:
            command = self.value[0]
        # This one is quite simple. It just calls ShellExecute.
        try:
            head, tail = os.path.split(self.plugin.foobar2000Path)
            return ShellExecute(0, None, tail, command, head, 1)
        except:
            # Some error-checking is always fine.
            raise self.Exceptions.ProgramNotFound


# Now we can start to define the plugin by sub-classing eg.PluginClass 
Example #5
Source File: win32print_driver.py    From pywebdriver with GNU General Public License v3.0 5 votes vote down vote up
def printPdf(self, printer, data):
            defaultPrinter = win32print.GetDefaultPrinter()
            win32print.SetDefaultPrinter(printer)
            with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:
                f.write(base64.b64decode(data))
                f.flush()
                filename = os.path.basename(f.name)
                dirname = os.path.dirname(f.name)
                win32api.ShellExecute(0, "print", filename, None, dirname, 0)
            win32print.SetDefaultPrinter(defaultPrinter)
            return 0 
Example #6
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self,label,cmdline):
        try:
            head, tail = os.path.split(self.plugin.IrfanViewPath)
            return win32api.ShellExecute(
                0,
                None,
                tail,
                cmdline.encode(myEncoding),
                head,
                1
            )
        except:
            self.PrintError(self.text.err) 
Example #7
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def OpenHelpPage(self,html_page):
        try:
            head, tail = os.path.split(self.IrfanViewPath)
            return win32api.ShellExecute(
                0,
                None,
                "hh.exe",
                ('mk:@MSITStore:'+head+'\i_view32.chm::/'\
                +html_page).encode(myEncoding),
                os.environ['SYSTEMROOT'],
                1
            )
        except:
            self.PrintError(self.text.err) 
Example #8
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self, cmdLineArgs=""):
        vlcPath = GetVlcPath()
        return ShellExecute(
            0,
            None,
            vlcPath,
            self.GetCmdLineArgs(cmdLineArgs),
            None, #os.path.dirname(vlcPath),
            1
        ) 
Example #9
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def Execute(self, exe, path):
        try:
            res = ShellExecute(
                0,
                None,
                exe,
                None,
                path,
                1
            )
        except:
            res = None
            self.PrintError(self.text.text2 % exe)
        return res 
Example #10
Source File: demoutils.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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") 
Example #11
Source File: __init__.py    From pyrexecd with MIT License 5 votes vote down vote up
def shellopen(cmd, path, cwd=None):
    return win32api.ShellExecute(None, cmd, path, None, cwd,
                                 win32con.SW_SHOWDEFAULT) 
Example #12
Source File: help.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #13
Source File: demoutils.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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") 
Example #14
Source File: app.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def OnButHomePage(self, id, code):
		if code == win32con.BN_CLICKED:
			win32api.ShellExecute(0, "open", "http://starship.python.net/crew/mhammond/win32", None, "", 1) 
Example #15
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 4 votes vote down vote up
def __call__(self, kwargs):
        options = self.defaults.copy()
        options.update(kwargs)
        head, tail = os.path.split(self.plugin.IrfanViewPath)
        cp = SafeConfigParser()
        cp.optionxform = str #Case sensitive !
        cp.read(head+"\\i_view32.ini")
        if cp.has_option('Others','INI_Folder'):
            INI_Folder = cp.get('Others','INI_Folder',True)
            if INI_Folder == '%APPDATA%\\IrfanView':
                INI_Folder = eg.folderPath.RoamingAppData+"\\IrfanView\\"
            cp.read(INI_Folder+"\\i_view32.ini")
        sec="Slideshow"
        if not cp.has_section(sec):
            cp.add_section(sec)
        cp.set(sec, "WindowW", str(int(options["width_"])))
        cp.set(sec, "WindowH", str(int(options["high_"])))
        cp.set(sec, "AutoDelay", str(options["delay_"]))
        cp.set(sec, "RandomDelay", str(options["delay_"]))
        cp.set(sec, "PlayInWindow", str(options["mode_"]))
        cp.set(sec, "Advancement", str(options["progress_"]+1))
        cp.set(sec, "Loop", str(int(options["loop_"])))
        cp.set(sec, "NoSameImageAgain", str(int(options["noRepeat_"])))
        cp.set(sec, "SuppressErrors", str(int(options["suppress_"])))
        cp.set(sec, "ShowFilename", str(int(options["displText_"])))
        cp.set(sec, "LoopAudio", str(int(options["soundLoop_"])))
        cp.set(sec, "HideCursor", str(int(options["hideCursor_"])))
        cp.set(sec,"StopAndClose",str(int(options["close_"])))
        if len(options["mask_"])>0:
            cp.set(sec, "Text", options["mask_"])
        sec="Viewing"
        if not cp.has_section(sec):
            cp.add_section(sec)
        cp.set(sec, "ShowFullScreen", str(options["fit_"]))
        cp.set(sec, "FSResample", str(int(options["resample_"])))
        cp.set(sec, "FSAlpha", str(int(options["alpha_"])))
        if cp.has_option('Others','INI_Folder'):
            cp.remove_option('Others','INI_Folder')
        fp = open(eg.folderPath.RoamingAppData+"\\EventGhost\\i_view32.ini",'wb')
        cp.write(fp)
        fp.close()
        params='/slideshow="'+(options["filepath_"] if options["source_"] \
            else options["dirpath_"])
        params+='" /ini="'+eg.folderPath.RoamingAppData+'\\EventGhost\\" /monitor='\
            +str(options["mon_"])
        try:
            return win32api.ShellExecute(
                0,
                None,
                tail,
                params.encode(myEncoding),
                head,
                1
            )
        except:
            self.PrintError(self.text.err) 
Example #16
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 4 votes vote down vote up
def __call__(self, kwargs):
        options = self.defaults.copy()
        options.update(kwargs)
        head, tail = os.path.split(self.plugin.IrfanViewPath)
        cp = SafeConfigParser()
        cp.optionxform = str #Case sensitive !
        cp.read(head+"\\i_view32.ini")
        if cp.has_option('Others','INI_Folder'):
            INI_Folder = cp.get('Others','INI_Folder',True)
            if INI_Folder == '%APPDATA%\\IrfanView':
                INI_Folder = eg.folderPath.RoamingAppData+"\\IrfanView\\"
            cp.read(INI_Folder+"\\i_view32.ini")
        sec="WinPosition"
        if not cp.has_section(sec):
            cp.add_section(sec)
        cp.set(sec, "Width", str(options["width_"]))
        cp.set(sec, "Height", str(options["high_"]))
        fp = open(head+"\\i_view32.ini",'wb')
        cp.write(fp)
        fp.close()
        sec="Viewing"
        if not cp.has_section(sec):
            cp.add_section(sec)
        cp.set(sec, "FSResample", str(int(options["resample_"])))
        cp.set(sec, "FSAlpha", str(int(options["alpha_"])))
        cp.set(sec, "HideCursor", str(int(options["hide_"])))
        cp.set(sec, "ShowFullScreenName", str(int(options["displ_"])))
        cp.set(sec, "UseResample", str(int(options["resample2_"])))
        cp.set(sec, "Centered", str(int(options["center_"])))
        cp.set(sec, "FullScreen", str(options["fullOrWin_"]))
        cp.set(sec, "FitWindowOption", str(options["winMode_"]+1))
        cp.set(sec, "ShowFullScreen", str(options["fullMode_"]))
        if len(options["mask_"])>0:
            cp.set(sec, "FullText", options["mask_"])
        if cp.has_option('Others','INI_Folder'):
            cp.remove_option('Others','INI_Folder')
        fp = open(eg.folderPath.RoamingAppData+"\\EventGhost\\i_view32.ini",'wb')
        cp.write(fp)
        fp.close()
        params=options["filepath_"]+' /hide='+str(8*options["caption_"]\
            +4*options["menuBar_"]+2*options["statusBar_"]+options["toolBar_"])
        params+=' /ini="'+eg.folderPath.RoamingAppData+'\\EventGhost\\" /pos=('\
            +str(options["xCoord_"])+','+str(options["yCoord_"])+')'
        if len(options["lineOpt_"])>0:
            params+=' '+options["lineOpt_"]
        #params+=' /monitor='+str(options["mon_"])
        try:
            return win32api.ShellExecute(
                0,
                None,
                tail,
                params.encode(myEncoding),
                head,
                1
            )
        except:
            self.PrintError(self.text.err) 
Example #17
Source File: demoutils.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
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")