def _windows_resolve(command): """ Try and find the full path and file extension of the executable to run. This is so that e.g. calls to 'somescript' will point at 'somescript.cmd' without the need to set shell=True in the subprocess. If the executable contains periods it is a special case. Here the win32api call will fail to resolve the extension automatically, and it has do be done explicitly. :param command: The command array to be run, with the first element being the command with or w/o path, with or w/o extension. :return: Returns the command array with the executable resolved with the correct extension. If the executable cannot be resolved for any reason the original command array is returned. """ try: import win32api except ImportError: if (2, 8) < sys.version_info < (3, 5): logger.info( "Resolving executable names only supported on Python 2.7 and 3.5+" ) else: logger.warning( "Could not resolve executable name: package win32api missing") return command if not command or not isinstance(command[0], six.string_types): return command try: _, found_executable = win32api.FindExecutable(command[0]) logger.debug("Resolved %s as %s", command[0], found_executable) return (found_executable, ) + tuple(command[1:]) except Exception as e: if not hasattr(e, "winerror"): raise # Keep this error message for later in case we fail to resolve the name logwarning = getattr(e, "strerror", str(e)) if "." in command[0]: # Special case. The win32api may not properly check file extensions, so # try to resolve the executable explicitly. for extension in os.getenv("PATHEXT").split(os.pathsep): try: _, found_executable = win32api.FindExecutable(command[0] + extension) logger.debug("Resolved %s as %s", command[0], found_executable) return (found_executable, ) + tuple(command[1:]) except Exception as e: if not hasattr(e, "winerror"): raise logger.warning("Error trying to resolve the executable: %s", logwarning) return command
def StartAcrobatReader(filename): global dde_server import win32api import win32ui import dde filename = unicode(os.path.abspath(filename)) path, name = os.path.split(filename) reader = win32api.FindExecutable(name, path) os.spawnl(os.P_NOWAIT, reader[1], " ") for t in range(10): time.sleep(1) for acrobat in DDE_ACROBAT_STRINGS: try: if not dde_server: dde_server = dde.CreateServer() dde_server.Create('Gertrude') c = dde.CreateConversation(dde_server) c.ConnectTo(acrobat, 'control') c.Exec('[DocOpen("%s")]' % (filename, )) return except Exception, e: pass print "Impossible de lancer acrobat reader ; prochain essai dans 1s ...", e
def _app_button_execute(self): dir_ = os.getcwdu() args = u'"%s"' % self.exePath args += u' '.join([u'%s' % arg for arg in self.exeArgs]) try: import win32api r, executable = win32api.FindExecutable(self.exePath.s) executable = win32api.GetLongPathName(executable) win32api.ShellExecute(0,u"open",executable,args,dir_,1) except Exception as error: if isinstance(error,WindowsError) and error.winerror == 740: # Requires elevated permissions try: import win32api win32api.ShellExecute(0,'runas',executable,args,dir_,1) except Exception as error: self.ShowError(error) else: # Most likely we're here because FindExecutable failed (no file association) # Or because win32api import failed. Try doing it using os.startfile # ...Changed to webbrowser.open because os.startfile is windows specific and is not cross platform compatible cwd = bolt.Path.getcwd() self.exePath.head.setcwd() try: webbrowser.open(self.exePath.s) except UnicodeError: self._showUnicodeError() except Exception as error: self.ShowError(error) finally: cwd.setcwd()
def finalize_options(self): py2exe.build_exe.py2exe.finalize_options(self) if self.makensis is None: try: import win32api self.makensis = win32api.FindExecutable('makensis') except: # Default path for makensis. This is where it gets # installed by default. self.makensis = os.path.join(os.environ['ProgramFiles'], 'NSIS\\makensis')
def _find(command): """Try to find the executable file path of given `command` using ``win32api.FindExecutable()``. """ try: status, path = win32api.FindExecutable(command) except pywintypes.error: # try again with where.exe # (FindExecutable fails for commands with dots) return _where(command) return path
def find_git_command(): """Find command to run for system Git (usually C Git). """ if sys.platform == 'win32': # support .exe, .bat and .cmd try: # to avoid overhead import win32api except ImportError: # run through cmd.exe with some overhead return ['cmd', '/c', 'git'] else: status, git = win32api.FindExecutable('git') return [git] else: return ['git']
def is_exe(fpath): # just msi files are still executed - com, exe, bat files are blocked # send_message('{"debug": "hello"}') # helpful resource http://timgolden.me.uk/python/win32_how_do_i/tell-if-a-file-is-executable.html try: # print "Looking at", filePath r, executable = win32api.FindExecutable(fpath) executable = win32api.GetLongPathName(executable).lower() except pywintypes.error: # print "Neither executable nor document" # e.g. just a path return False else: return executable == fpath.lower()
def main(): # proc = subprocess.Popen("C:\\Program Files (x86)\\Leap Motion\\Core Services\\VisualizerApp.exe", stdin=subprocess.PIPE, stderr=subprocess.STDOUT) # time.sleep(1) # try: # proc.stdin.write(b'f') # except: # print("Killing") # proc.kill() _, cmd = win32api.FindExecutable('"C:\\Program Files (x86)\\Leap Motion\\Core Services\\VisualizerApp.exe"') time.sleep(1) _, _, pid, tid = win32process.CreateProcess( None, # name cmd, # command line None, # process attributes None, # thread attributes 0, # inheritance flag 0, # creation flag None, # new environment None, # current directory win32process.STARTUPINFO ()) def wcallb(hwnd, handle): handle[win32gui.GetClassName(hwnd)] = hwnd win32gui.EnumChildWindows(hwnd, wcallb, handle) return True handle = {} while not handle: # loop until the window is loaded time.sleep(0.5) win32gui.EnumThreadWindows(tid, wcallb, handle) win32api.PostMessage( handle['FREEGLUT'], win32con.WM_CHAR, ord("f"), 0) # Create a sample listener and controller listener = SampleListener() controller = Leap.Controller() listener.add_handle(handle) # Have the sample listener receive events from the controller controller.add_listener(listener) # Keep this process running until Enter is pressed print("Press Enter to quit...") sys.stdout.flush() try: sys.stdin.readline() except KeyboardInterrupt: pass finally: # Remove the sample listener when done controller.remove_listener(listener)
def get_external_program_location(key): extensions = ["", ".exe"] potential_names = ["%s%s" % (key, ext) for ext in extensions] windows_program_directories = { 'inkscape': ['Inkscape'], 'pstoedit': ['pstoedit'] } # check the windows path via win32api try: import win32api location = win32api.FindExecutable(key)[1] if location: return location except Exception: # Wildcard (non-system exiting) exception to match "ImportError" and # "pywintypes.error" (for "not found"). pass # go through the PATH environment variable if "PATH" in os.environ: path_env = os.environ["PATH"] for one_dir in path_env.split(os.pathsep): for basename in potential_names: location = os.path.join(one_dir, basename) if os.path.isfile(location): return location # do a manual scan in the programs directory (only for windows) program_dirs = ["C:\\Program Files", "C:\\Programme"] try: from win32com.shell import shellcon, shell # The frozen application somehow dows not provide this setting. program_dirs.insert( 0, shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILES, 0, 0)) except ImportError: # no other options for non-windows systems pass # scan the program directory for program_dir in program_dirs: for sub_dir in windows_program_directories[key]: for basename in potential_names: location = os.path.join(program_dir, sub_dir, basename) if os.path.isfile(location): return location # nothing found return None
def Restart(self): path = os.getcwd() if sys.platform == "win32": import win32api executable = win32api.FindExecutable(u'tribler.exe')[1] elif sys.platform == "linux2": executable = os.path.join(self.utility.session.get_install_dir(), 'Tribler', 'Main', "tribler.py") elif sys.platform == "darwin": executable = "?" if sys.platform != "win32": executable = os.path.join(path, executable) self._logger.info(repr(executable)) def start_tribler(): try: subprocess.Popen(executable) except: print_exc() atexit.register(start_tribler) self.Close(force=True)
def Execute(self): if not self.IsPresent(): balt.showError(Link.Frame, _(u'Application missing: %s') % self.exePath.s, _(u"Could not launch '%s'" % self.exePath.stail)) return if self.isShortcut or self.isFolder: webbrowser.open(self.exePath.s) elif self.isJava: cwd = bolt.Path.getcwd() if self.workingDir: self.workingDir.setcwd() else: self.jar.head.setcwd() try: subprocess.Popen( (self.java.stail, u'-jar', self.jar.stail, self.appArgs), executable=self.java.s, close_fds=True) except UnicodeError: self._showUnicodeError() except Exception as error: self.ShowError(error) finally: cwd.setcwd() elif self.isExe: exeObse = bass.dirs['app'].join(bush.game.se.exe) exeLaa = bass.dirs['app'].join(bush.game.laa.exe) if BashStatusBar.laaButton.button_state and \ self.exePath.tail == bush.game.launch_exe: # Should use the LAA Launcher exePath = exeLaa args = [exePath.s] elif self.obseArg is not None and \ BashStatusBar.obseButton.button_state: if bass.inisettings[ 'SteamInstall'] and self.exePath.tail == u'Oblivion.exe': exePath = self.exePath else: exePath = exeObse args = [exePath.s] if self.obseArg != u'': args.append(u'%s' % self.obseArg) else: exePath = self.exePath args = [exePath.s] args.extend(self.exeArgs) if self.extraArgs: args.extend(self.extraArgs) Link.Frame.SetStatusInfo(u' '.join(args[1:])) cwd = bolt.Path.getcwd() if self.workingDir: self.workingDir.setcwd() else: exePath.head.setcwd() try: popen = subprocess.Popen(args, close_fds=True) if self.wait: popen.wait() except UnicodeError: self._showUnicodeError() except WindowsError as werr: if werr.winerror != 740: self.ShowError(werr) try: import win32api win32api.ShellExecute(0, 'runas', exePath.s, u'%s' % self.exeArgs, bass.dirs['app'].s, 1) except: self.ShowError(werr) except Exception as error: self.ShowError(error) finally: cwd.setcwd() else: dir_ = self.workingDir.s if self.workingDir else bolt.Path.getcwd( ).s args = u'"%s"' % self.exePath.s args += u' '.join([u'%s' % arg for arg in self.exeArgs]) try: import win32api r, executable = win32api.FindExecutable(self.exePath.s) executable = win32api.GetLongPathName(executable) win32api.ShellExecute(0, u"open", executable, args, dir_, 1) except Exception as error: if isinstance(error, WindowsError) and error.winerror == 740: # Requires elevated permissions try: import win32api win32api.ShellExecute(0, 'runas', executable, args, dir_, 1) except Exception as error: self.ShowError(error) else: # Most likely we're here because FindExecutable failed (no file association) # Or because win32api import failed. Try doing it using os.startfile # ...Changed to webbrowser.open because os.startfile is windows specific and is not cross platform compatible cwd = bolt.Path.getcwd() if self.workingDir: self.workingDir.setcwd() else: self.exePath.head.setcwd() try: webbrowser.open(self.exePath.s) except UnicodeError: self._showUnicodeError() except Exception as error: self.ShowError(error) finally: cwd.setcwd()
def main(): if sys.platform == 'win32': import win32api for directory in ("./dist", "./build"): if os.path.isdir(directory): shutil.rmtree(directory) os.chdir("WinPython-32bit-2.7.13.1Zero") paths = [ "notebooks", "scripts", "settings", "tools" ] + glob.glob("*.exe") + glob.glob("python-2.7.13/Scripts/*.exe") paths += [ ("python-2.7.13/" + path) for path in ("NEWS.txt", "README.txt", "w9xpopen.exe", "Doc", "include", "Logs", "tcl", "Lib\site-packages\prompt_toolkit", "Lib\site-packages\pygments", "Lib\site-packages\setuptools", "Lib\ensurepip", "Lib\site-packages\win32\Demos", "Lib\site-packages\pip", "Lib\site-packages\jedi", "Lib/unittest", "Lib/test", "Lib/lib2to3", "Lib/lib-tk", "Lib/idlelib", "Lib/distutils", "Lib/ctypes", "Lib/compiler", "Lib/site-packages/wx/tools/Editra", "Lib/site-packages/wx/tools/XRCed") ] for root, dirnames, filenames in os.walk('python-2.7.13'): for filename in fnmatch.filter( filenames, '*.pyc') + fnmatch.filter(filenames, '*.chm'): paths.append(os.path.join(root, filename)) # for filename in filenames: # if os.stat(os.path.join(root, filename)).st_size > 10000: # print os.path.join(root, filename), os.stat(os.path.join(root, filename)).st_size for path in paths: print "Remove %s" % path if os.path.isdir(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) os.chdir("..") issfile = "setup.iss" isscontents = file(issfile + ".template").read() isscontents = isscontents.replace("@VERSION@", VERSION) file(issfile, "w").write(isscontents) path, name = os.path.split(issfile) isspath = os.path.split(win32api.FindExecutable(name, path)[-1])[0] if not os.system('\"%s\ISCC.exe\" %s' % (isspath, issfile)): exe = "./Output/setup_%s.exe" % VERSION if os.path.isfile(exe): os.remove(exe) os.rename("./Output/setup.exe", exe) print u"File %s generated (%d bytes)" % (exe, os.stat(exe).st_size) elif sys.platform == 'darwin': from setuptools import setup APP = ["gertrude.pyw"] DATA_FILES = glob.glob("bitmaps_dist/*.png") + glob.glob( "bitmaps_dist/*.ico") + glob.glob( "templates_dist/*.html") + glob.glob( "templates_dist/*.txt") + glob.glob("templates_dist/*.od?") OPTIONS = { 'site_packages': True, 'arch': 'i386', 'iconfile': 'bitmaps_dist/gertrude.icns', 'argv_emulation': True, 'includes': ["bcrypt", "_cffi_backend", "requests"], 'packages': ["requests"] } setup(name="Gertrude", app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=["py2app", "requests"], install_requires=["requests"]) elif "linux" in sys.platform: if not os.path.exists("./gertrude.py"): os.symlink("./gertrude.pyw", "./gertrude.py") from py2deb import Py2deb p = Py2deb("gertrude") p.author = "Bertrand Songis" p.mail = "*****@*****.**" p.description = u"Logiciel de gestion de creches" p.url = "http://www.gertrude-logiciel.org" p.icon = "./bitmaps_dist/gertrude.png" p.depends = "bash, python, python-gtk2, python-bcrypt, python-wxgtk2.8 | python-wxgtk3.0, python-requests" p.license = "gpl" p.section = "utils" p.arch = "all" p["/usr/share/applications"] = [ "./linux/gertrude.desktop|gertrude.desktop" ] p["/usr/share/gertrude"] = glob.glob("./*.py") + glob.glob( "./demo.db") + glob.glob("./bitmaps_dist/*.*") + glob.glob( "./bitmaps_dist/pictos/*" ) + glob.glob("./templates_dist/*.html") + glob.glob( "./templates_dist/*.txt") + glob.glob("./templates_dist/*.od?") p["/usr/bin"] = ["./linux/gertrude|gertrude"] p["/usr/share/doc/gertrude"] = ["COPYING"] p.generate(VERSION, u"", rpm=True, src=True) else: print u"Plateforme %s non supportée" % sys.platform
import win32api as winapi import psutil # import stem find a usage for this later. try: print(winapi.GetComputerName("ComputerNameNetBIOS")) print(winapi.GetComputerName("ComputerNamePhysicalDnsDomain")) print(winapi.GetComputerName("ComputerNameDnsDomain")) print(winapi.GetSystemDirectory("C:\\Windows\\System32")) # <-- Need to give users options for directories they want to scan print(winapi.GetLastInputInfo()) print(psutil.disk_partitions()) print(psutil.disk_usage("/")) print(psutil.disk_io_counters()) PROC_NAMES = ["Taskmgr.exe", "browser_broker.exe", "ProcNetMonitor.exe", "proc_watch.exe", "taskhost.exe", "Task Explorer.exe", "Procmon.exe", "procexp.exe", "pskill.exe", "Psinfo.exe", "PsGetsid", "Psinfo.exe", "portmon.exe"] for item in PROC_NAMES: for proc in psutil.process_iter(): if proc.name() == item: prox = set() prox.add(str(proc)) for item in prox: print(item) for item in PROC_NAMES: print(winapi.FindExecutable(item)) except Exception as e: print("something broke.....\n{}".format(e))