Exemplo n.º 1
0
def LocatePythonServiceExe(exeName = None):
    if not exeName and hasattr(sys, "frozen"):
        # If py2exe etc calls this with no exeName, default is current exe.
        return sys.executable

    # Try and find the specified EXE somewhere.  If specifically registered,
    # use it.  Otherwise look down sys.path, and the global PATH environment.
    if exeName is None:
        if os.path.splitext(win32service.__file__)[0].endswith("_d"):
            exeName = "PythonService_d.exe"
        else:
            exeName = "PythonService.exe"
    # See if it exists as specified
    if os.path.isfile(exeName): return win32api.GetFullPathName(exeName)
    baseName = os.path.splitext(os.path.basename(exeName))[0]
    try:
        exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE,
                                         "Software\\Python\\%s\\%s" % (baseName, sys.winver))
        if os.path.isfile(exeName):
            return exeName
        raise RuntimeError("The executable '%s' is registered as the Python " \
                           "service exe, but it does not exist as specified" \
                           % exeName)
    except win32api.error:
        # OK - not there - lets go a-searchin'
        for path in [sys.prefix] + sys.path:
            look = os.path.join(path, exeName)
            if os.path.isfile(look):
                return win32api.GetFullPathName(look)
        # Try the global Path.
        try:
            return win32api.SearchPath(None, exeName)[0]
        except win32api.error:
            msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % (exeName, exeName)
            raise error(msg)
Exemplo n.º 2
0
def main(argv):
    # Must write out a no-op shell script before any error can happen
    # otherwise the script from the previous run could result.
    try:
        shellScript = os.environ[_envvar]
    except KeyError:
        if _subsystem == "windows":
            pass  # Don't complain about missing console setup.
        return setup()
    else:
        generateShellScript(shellScript)  # no-op, overwrite old one

    # Parse options
    try:
        shortopts = "hVcpsadlo"
        longopts = [
            'help', 'version', 'cd', 'print', 'set', 'add-current', 'delete',
            'list', 'open'
        ]
        optlist, args = getopt.getopt(argv[1:], shortopts, longopts)
    except getopt.GetoptError as ex:
        msg = ex.msg
        if ex.opt in ('d', 'dump'):
            msg += ": old -d|--dump option is now -l|--list"
        sys.stderr.write("go: error: %s.\n" % msg)
        sys.stderr.write("See 'go --help'.\n")
        return 1
    action = "cd"
    for opt, optarg in optlist:
        if opt in ('-h', '--help'):
            sys.stdout.write(__doc__)
            return 0
        elif opt in ('-V', '--version'):
            sys.stdout.write("go %s\n" % __version__)
            return 0
        elif opt in ('-c', '--cd'):
            action = "cd"
        elif opt in ('-p', '--print'):
            action = "print"
        elif opt in ('-s', '--set'):
            action = "set"
        elif opt in ('-a', '--add-current'):
            action = "add"
        elif opt in ('-d', '--delete'):
            action = "delete"
        elif opt in ('-l', '--list'):
            action = "list"
        elif opt in ("-o", "--open"):
            action = "open"

    # Parse arguments and do specified action.
    if action == "add":
        if len(args) != 1:
            error("Incorrect number of arguments. argv: %s" % argv)
            return 1
        name, value = args[0], os.getcwd()
        try:
            setShortcut(name, value)
        except GoError as ex:
            error(str(ex))
            return 1

    elif action == "delete":
        if len(args) != 1:
            error("Incorrect number of arguments. argv: %s" % argv)
            return 1
        name, value = args[0], None
        try:
            setShortcut(name, value)
        except GoError as ex:
            error(str(ex))
            return 1

    elif action == "set":
        if len(args) != 2:
            error("Incorrect number of arguments. argv: %s" % argv)
            return 1
        name, value = args
        try:
            setShortcut(name, value)
        except GoError as ex:
            error(str(ex))
            return 1

    elif action == "cd":
        if len(args) > 1:
            error("Incorrect number of arguments. argv: %s" % argv)
            # error("Usage: go [options...] shortcut[/subpath]")
            return 1

        if len(args) == 1:
            path = args[0]
        else:
            path = getHomeDir()

        if _subsystem == "console":

            try:
                generateShellScript(shellScript, path)
            except KeyError as ex:
                error("Unrecognized shortcut: '%s'" % str(ex))
                return 1
            except GoError as ex:
                error(str(ex))
                return 1
        elif _subsystem == "windows" and sys.platform.startswith("win"):
            try:
                dir = resolvePath(path)
            except GoError as ex:
                error("Error resolving '%s': %s" % (path, ex))
                return 1
            try:
                comspec = os.environ["COMSPEC"]
            except KeyError:
                error("Could not determine shell. No COMSPEC environment "
                      "variable.")
                return 1

            argv = [
                comspec,
                "/k",  # Does command.com support '/k'?
                "cd",
                "/D",
                '"%s"' % dir
            ]
            if os.path.basename(comspec).lower() == "cmd.exe":
                argv += ["&&", "title", '%s' % dir]

            os.spawnv(os.P_NOWAIT, comspec, argv)

        else:
            error("Internal error: subsystem is 'windows' and platform is "
                  "not win32")
            return 1
    elif action == "print":
        if len(args) != 1:
            error("Incorrect number of arcuments. argv: %s" % argv)
            return 1

        try:
            path = resolvePath(args[0])
            print(path)
        except GoError as ex:
            error(ex)
            return 1

    elif action == "list":
        if len(args) == 0:
            printShortcuts(getShortcuts())
        elif len(args) == 1:
            pattern = args[0].lower()
            shortcuts = getShortcuts()
            s = {}
            for name, value in list(shortcuts.items()):
                if name.lower().find(pattern) != -1:
                    s[name] = value
            printShortcuts(s, "Matching '%s'" % pattern)
        else:
            error("Incorrect number of arguments. argv: %s" % argv)
            return 1

    elif action == "open":

        if len(args) > 1:
            error("Incorrect number of arguments. argv: %s" % argv)
            return 1
        elif len(args) == 0:
            args.append(os.getcwd())

        path = args[0]

        try:
            dir = resolvePath(path)
        except GoError as ex:
            error("Error resolving '%s': %s" % (path, ex))
            return 1

        if sys.platform.startswith("win") and \
                list(os.environ.keys()).count(_fileman_env) == 0:
            try:
                import win32api
                try:
                    explorerExe, offset = win32api.SearchPath(
                        None, "explorer.exe")
                except win32api.error as ex:
                    error("Could not find 'explorer.exe': %s" % ex)
                    return 1
            except ImportError:
                explorerExe = _findOnPath("explorer.exe")
                if explorerExe == 0:
                    error("Could not find path to Explorer.exe")
                    return 1

            os.spawnv(os.P_NOWAIT, explorerExe, [explorerExe, '/E,"%s"' % dir])
        else:
            try:
                if sys.platform.startswith('darwin') and \
                        list(os.environ.keys()).count(_fileman_env) == 0:
                    fileMan = '/usr/bin/open'
                else:
                    fileMan = os.environ[_fileman_env]
                if not os.path.exists(fileMan):
                    fileMan = _findOnPath(fileMan)
                    if fileMan == 0:
                        error("Could not find path to '%s'" % fileMan)
                        return 1
                os.spawnv(os.P_NOWAIT, fileMan, [fileMan, dir])

            except KeyError:
                error("No file manager found.  Set the %s environment variable"
                      " to set one." % _fileman_env)

    else:
        error("Internal Error: unknown action: '%s'\n")
        return 1
Exemplo n.º 3
0
    # Check the MFC dll exists - it is doesn't, point them at it
    # (I should install it, but its a bit tricky with distutils)
    # Unfortunately, this is quite likely on Windows XP and MFC71.dll
    if sys.hexversion < 0x2060000:
        mfc_dll = "mfc71.dll"
    elif sys.hexversion < 0x2070000:
        mfc_dll = "mfc90.dll"
    elif sys.hexversion < 0x3000000:
        mfc_dll = "mfc90u.dll"
    else:
        mfc_dll = "mfc100u.dll"
    try:
        # It might be next to pythonwin itself (which is where setup.py
        # currently arranges for it to be installed...)
        if not os.path.isfile(os.path.join(lib_dir, "pythonwin", mfc_dll)):
            win32api.SearchPath(None, mfc_dll)
    except win32api.error:
        print "*" * 20, "WARNING", "*" * 20
        print "It appears that the MFC DLL '%s' is not installed" % (mfc_dll, )
        print "Pythonwin will not work without this DLL, and I haven't had the"
        print "time to package it in with the installer."
        print
        print "You can download this DLL from:"
        print "http://starship.python.net/crew/mhammond/win32/"
        print "*" * 50

    # importing win32com.client ensures the gen_py dir created - not strictly
    # necessary to do now, but this makes the installation "complete"
    try:
        import win32com.client
    except ImportError:
Exemplo n.º 4
0
def install():
    import distutils.sysconfig
    import traceback
    # The .pth file is now installed as a regular file.
    # Create the .pth file in the site-packages dir, and use only relative paths
    lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1)
    # We used to write a .pth directly to sys.prefix - clobber it.
    if os.path.isfile(os.path.join(sys.prefix, "pywin32.pth")):
        os.unlink(os.path.join(sys.prefix, "pywin32.pth"))
    # The .pth may be new and therefore not loaded in this session.
    # Setup the paths just in case.
    for name in "win32 win32\\lib Pythonwin".split():
        sys.path.append(os.path.join(lib_dir, name))
    # It is possible people with old versions installed with still have
    # pywintypes and pythoncom registered.  We no longer need this, and stale
    # entries hurt us.
    for name in "pythoncom pywintypes".split():
        keyname = "Software\\Python\\PythonCore\\" + sys.winver + "\\Modules\\" + name
        for root in winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER:
            try:
                winreg.DeleteKey(root, keyname + "\\Debug")
            except WindowsError:
                pass
            try:
                winreg.DeleteKey(root, keyname)
            except WindowsError:
                pass
    LoadSystemModule(lib_dir, "pywintypes")
    LoadSystemModule(lib_dir, "pythoncom")
    import win32api
    # and now we can get the system directory:
    files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*"))
    if not files:
        raise RuntimeError("No system files to copy!!")
    # Try the system32 directory first - if that fails due to "access denied",
    # it implies a non-admin user, and we use sys.prefix
    for dest_dir in [get_system_dir(), sys.prefix]:
        # and copy some files over there
        worked = 0
        try:
            for fname in files:
                base = os.path.basename(fname)
                dst = os.path.join(dest_dir, base)
                CopyTo("installing %s" % base, fname, dst)
                if verbose:
                    print("Copied %s to %s" % (base, dst))
                # Register the files with the uninstaller
                file_created(dst)
                worked = 1
                # If this isn't sys.prefix (ie, System32), then nuke
                # any versions that may exist in sys.prefix - having
                # duplicates causes major headaches.
                if dest_dir != sys.prefix:
                    bad_fname = os.path.join(sys.prefix, base)
                    if os.path.exists(bad_fname):
                        # let exceptions go here - delete must succeed
                        os.unlink(bad_fname)
            if worked:
                break
        except win32api.error as details:
            if details.winerror == 5:
                # access denied - user not admin - try sys.prefix dir,
                # but first check that a version doesn't already exist
                # in that place - otherwise that one will still get used!
                if os.path.exists(dst):
                    msg = "The file '%s' exists, but can not be replaced " \
                          "due to insufficient permissions.  You must " \
                          "reinstall this software as an Administrator" \
                          % dst
                    print(msg)
                    raise RuntimeError(msg)
                continue
            raise
    else:
        raise RuntimeError(
            "You don't have enough permissions to install the system files")

    # Pythonwin 'compiles' config files - record them for uninstall.
    pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin")
    for fname in glob.glob(os.path.join(pywin_dir, "*.cfg")):
        file_created(fname[:-1] + "c")  # .cfg->.cfc

    # Register our demo COM objects.
    try:
        try:
            RegisterCOMObjects()
        except win32api.error as details:
            if details.winerror != 5:  # ERROR_ACCESS_DENIED
                raise
            print("You do not have the permissions to install COM objects.")
            print("The sample COM objects were not registered.")
    except:
        print("FAILED to register the Python COM objects")
        traceback.print_exc()

    # There may be no main Python key in HKCU if, eg, an admin installed
    # python itself.
    winreg.CreateKey(get_root_hkey(), root_key_name)

    # Register the .chm help file.
    chm_file = os.path.join(lib_dir, "PyWin32.chm")
    if os.path.isfile(chm_file):
        # This isn't recursive, so if 'Help' doesn't exist, we croak
        SetPyKeyVal("Help", None, None)
        SetPyKeyVal("Help\\Pythonwin Reference", None, chm_file)
    else:
        print("NOTE: PyWin32.chm can not be located, so has not " \
              "been registered")

    # misc other fixups.
    fixup_dbi()

    # Register Pythonwin in context menu
    try:
        RegisterPythonwin()
    except:
        print('Failed to register pythonwin as editor')
        traceback.print_exc()
    else:
        if verbose:
            print('Pythonwin has been registered in context menu')

    # Create the win32com\gen_py directory.
    make_dir = os.path.join(lib_dir, "win32com", "gen_py")
    if not os.path.isdir(make_dir):
        if verbose:
            print("Creating directory", make_dir)
        directory_created(make_dir)
        os.mkdir(make_dir)

    try:
        # create shortcuts
        # CSIDL_COMMON_PROGRAMS only available works on NT/2000/XP, and
        # will fail there if the user has no admin rights.
        fldr = get_shortcuts_folder()
        # If the group doesn't exist, then we don't make shortcuts - its
        # possible that this isn't a "normal" install.
        if os.path.isdir(fldr):
            dst = os.path.join(fldr, "PythonWin.lnk")
            create_shortcut(os.path.join(lib_dir, "Pythonwin\\Pythonwin.exe"),
                            "The Pythonwin IDE", dst, "", sys.prefix)
            file_created(dst)
            if verbose:
                print("Shortcut for Pythonwin created")
            # And the docs.
            dst = os.path.join(fldr, "Python for Windows Documentation.lnk")
            doc = "Documentation for the PyWin32 extensions"
            create_shortcut(chm_file, doc, dst)
            file_created(dst)
            if verbose:
                print("Shortcut to documentation created")
        else:
            if verbose:
                print("Can't install shortcuts - %r is not a folder" %
                      (fldr, ))
    except Exception as details:
        print(details)

    # Check the MFC dll exists - it is doesn't, point them at it
    # (I should install it, but its a bit tricky with distutils)
    # Unfortunately, this is quite likely on Windows XP and MFC71.dll
    if sys.hexversion < 0x2060000:
        mfc_dll = "mfc71.dll"
    elif sys.hexversion < 0x2070000:
        mfc_dll = "mfc90.dll"
    elif sys.hexversion < 0x3000000:
        mfc_dll = "mfc90u.dll"
    else:
        mfc_dll = "mfc100u.dll"
    try:
        # It might be next to pythonwin itself (which is where setup.py
        # currently arranges for it to be installed...)
        if not os.path.isfile(os.path.join(lib_dir, "pythonwin", mfc_dll)):
            win32api.SearchPath(None, mfc_dll)
    except win32api.error:
        print("*" * 20, "WARNING", "*" * 20)
        print("It appears that the MFC DLL '%s' is not installed" %
              (mfc_dll, ))
        print(
            "Pythonwin will not work without this DLL, and I haven't had the")
        print("time to package it in with the installer.")
        print()
        print("You can download this DLL from:")
        print("http://starship.python.net/crew/mhammond/win32/")
        print("*" * 50)

    # importing win32com.client ensures the gen_py dir created - not strictly
    # necessary to do now, but this makes the installation "complete"
    try:
        import win32com.client
    except ImportError:
        # Don't let this error sound fatal
        pass
    print("The pywin32 extensions were successfully installed.")
Exemplo n.º 5
0
    elif action == "open" and sys.platform.startswith("win"):
        if len(args) != 1:
            error("Incorrect number of arguments. argv: %s" % argv)
            return 1
        path = args[0]

        try:
            dir = resolvePath(path)
        except GoError, ex:
            error("Error resolving '%s': %s" % (path, ex))
            return 1

        import win32api
        try:
            explorerExe, offset = win32api.SearchPath(None, "explorer.exe")
        except win32api.error, ex:
            error("Could not find 'explorer.exe': %s" % ex)
            return 1

        os.spawnv(os.P_NOWAIT, explorerExe, [explorerExe, '/E,"%s"' % dir])

    else:
        error("Internal Error: unknown action: '%s'\n")
        return 1
        

if __name__ == "__main__":
    if _subsystem == "windows":
        try:
            retval = main(sys.argv)
Exemplo n.º 6
0
print(api.GetFullPathName('.'))
print(api.GetLocalTime())
print(api.GetLogicalDriveStrings().replace('\x00', ' '))
print(api.GetLogicalDrives())
print(api.GetLongPathName('C:'))
print(api.GetModuleFileName(0))
print(api.GetNativeSystemInfo())
print(hex(api.GetSysColor(con.COLOR_WINDOW)))
print(api.GetSystemDirectory())
print(api.GetSystemInfo())
print(api.GetSystemMetrics(con.SM_CXSCREEN))
print(api.GetSystemTime())
print(api.GetTickCount())
# print(api.GetTimeZoneInformation())
print(api.GetUserDefaultLangID())
print(api.GetUserName())
print(api.GetVersion())
print(api.GetVolumeInformation('C:'))
print(api.GetWindowsDirectory())
print(api.GlobalMemoryStatus())
print(api.MessageBeep())
print(api.MessageBox(0, 'hello', 'world', con.MB_OK))
size = api.RegQueryInfoKey(con.HKEY_LOCAL_MACHINE)
print(size)
for i in range(size[0]):
    print(api.RegEnumKey(con.HKEY_LOCAL_MACHINE, i))
try:
    print(api.SearchPath('.', 'win32con.txt'))
except:
    print('error')
print(api.WinExec('Notepad'))