Pywin32 установка на windows

pywin32


This is the readme for the Python for Win32 (pywin32) extensions, which provides access to many of the Windows APIs from Python.

Docs

The docs are a long and sad story, but there’s now an online version of the helpfile that ships with the installers (thanks @ofek!). Lots of that is very old, but some is auto-generated and current. Would love help untangling the docs!

Support

Feel free to open issues for all bugs (or suspected bugs) in pywin32. pull-requests for all bugs or features are also welcome.

However, please do not open github issues for general support requests, or for problems or questions using the modules in this package – they will be closed. For such issues, please email the python-win32 mailing list – note that you must be subscribed to the list before posting.

Binaries

Binary releases are deprecated. While they are still provided, find them here

Installing via PIP

You should install pywin32 via pip – eg,

python -m pip install --upgrade pywin32

There is a post-install script (see below) which should not be run inside virtual environments; it should only be run in “global” installs.

For unreleased changes, you can download builds made by github actions – choose any “workflow” from the main branch and download its “artifacts”)

Installing globally

Outside of a virtual environment you might want to install COM objects, services, etc. You can do this by executing:

python Scripts/pywin32_postinstall.py -install

From the root of your Python installation.

If you do this with normal permissions it will be global for your user (a few files will be copied to the root of your Python install and some changes made to HKCU). If you execute this from an elevated process, it will be global for the machine (files will be copied to System32, HKLM will be changed, etc)

Running as a Windows Service

To run as a service, you probably want to install pywin32 globally from an elevated command prompt – see above.

You also need to ensure Python is installed in a location where the user running the service has access to the installation and is able to load pywintypesXX.dll and pythonXX.dll. In particular, the LocalSystem account typically will not have access to your local %USER% directory structure.

Troubleshooting

If you encounter any problems when upgrading like the following:

The specified procedure could not be found
Entry-point not found

It usually means one of 2 things:

  • You’ve upgraded an install where the post-install script has previously run. So you should run it again:

    python Scripts/pywin32_postinstall.py -install

    This will make some small attempts to cleanup older conflicting installs.

  • There are other pywin32 DLLs installed in your system, but in a different location than the new ones. This sometimes happens in environments that come with pywin32 pre-shipped (eg, anaconda?).

    The possible solutions here are:

    • Run the “post_install” script documented above.
    • Otherwise, find and remove all other copies of pywintypesXX.dll and pythoncomXX.dll (where XX is the Python version – eg, “39”)

Building from source

Install Visual Studio 2019 (later probably works, but options might be different), select “Desktop Development with C++”, then the following options:

  • Windows 10 SDK (latest offered I guess? At time of writing, 10.0.18362)
  • “C++ for MFC for …”
  • ARM build tools if necessary.

(the free compilers probably work too, but haven’t been tested – let me know your experiences!)

setup.py is a standard distutils build script, so you probably want:

or

Some modules need obscure SDKs to build – setup.py should succeed, gracefully telling you why it failed to build them – if the build actually fails with your configuration, please open an issue.

Release process

The following steps are performed when making a new release – this is mainly to form a checklist so @mhammond doesn’t forget what to do 🙂

  • Ensure CHANGES.txt has everything worth noting. Update the header to reflect the about-to-be released build and date, commit it.

  • Update setup.py with the new build number.

  • Execute make.bat, wait forever, test the artifacts.

  • Upload .whl artifacts to pypi – we do this before pushing the tag because they might be rejected for an invalid README.md. Done via py -3.? -m twine upload dist/*XXX*.whl.

  • Commit setup.py (so the new build number is in the repo), create a new git tag

  • Upload the .exe installers to github.

  • Update setup.py with the new build number + “.1” (eg, 123.1), to ensure future test builds aren’t mistaken for the real release.

  • Make sure everything is pushed to github, including the tag (ie, git push --tags)

  • Send mail to python-win32

Last Updated :
22 Sep, 2021

Pywin32 is a Python extension for windows that is used to access Windows API.  In this article, we will look into the process of installing Pywin32 on a windows machine.

Pre-requisites:

The only thing that you need for installing Numpy on Windows are:

  • Python 
  • PIP or Conda (depending upon user preference)

Installing Pywin32 on Windows using Conda:

If you want the installation to be done through conda,  open up the Anaconda Powershell Prompt and use the below command:

conda install -c anaconda pywin32

Type y for yes when prompted.

You will get a similar message once the installation is complete:

Installing Pywin32 on Windows using Conda

Make sure you follow the best practices for installation using conda as:

  • Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env

Note: If your preferred method of installation is conda-forge, use the below command:

conda config --env --add channels conda-forge

Verifying Pywin32 Installation on Windows using Conda:

To verify if Pywin32 has been successfully installed in your system run the below command in Anaconda Powershell Prompt:

conda list pywin32

You’ll get the below message if the installation is complete:

Verifying Pywin32 Installation on Windows using Conda

Installing Pywin32 on Windows using PIP:

If you want the installation to be done through PIP,  open up the Command Prompt and use the below command:

pip install pywin32 

You will get a similar message once the installation is complete:

Installing Pywin32 on Windows using PIP

Verifying Pywin32 Installation on Windows using PIP:

To verify if the Pywin32 has been successfully installed in your system run the below command in Command Prompt:

python -m pip show pywin32 

Verifying Pywin32 Installation on Windows using PIP

You’ll get the below message if the installation is complete:


This is the readme for the Python for Win32 (pywin32) extensions, which provides access to many of the Windows APIs from Python, including COM support.

See CHANGES.txt for recent notable changes.

adodbapi’s documentation can be found in: adodbapi/readme.txt

isapi’s documentation can be found in: isapi/README.txt

Docs

The docs are a long and sad story, but there’s now an online version
of the PyWin32.chm helpfile (thanks @ofek!).
Lots of that is very old, but some is auto-generated and current. Would love help untangling the docs!

You can get type hints, signatures and annotations from types-pywin32.

Support

Feel free to open issues for
all bugs (or suspected bugs) in pywin32. pull-requests
for all bugs or features are also welcome.

Type stubs currently live in typeshed.
Any issue or request related to static type-checking and IntelliSense should be raised there.

However, please do not open GitHub issues for general support requests, or
for problems or questions using the modules in this package — they will be
closed. For such issues, please email the
python-win32 mailing list —
note that you must be subscribed to the list before posting.

Binaries

Binary releases are no longer supported.

Build 306 was the last with .exe installers. You really shouldn’t use them, but if you really need them,
find them here

Installing via PIP

You should install pywin32 via pip — eg,

python -m pip install --upgrade pywin32

There is a post-install script (see below) which should not be run inside virtual environments;
it should only be run in «global» installs.

For unreleased changes, you can download builds made by github actions —
choose any «workflow» from the main branch and download its «artifacts»

Installing globally

Outside of a virtual environment you might want to install COM objects, services, etc. You can do
this by executing:

python -m pywin32_postinstall -install

or (shorter but you don’t have control over which python environment is used)

pywin32_postinstall -install

If you do this with normal permissions it will be global for your user (a few files will be
copied to the root of your Python install and some changes made to HKCU). If you execute this from
an elevated process, it will be global for the machine (files will be copied to System32, HKLM
will be changed, etc)

Installing for MingGW/msys2

The folks at https://github.com/msys2/MINGW-packages/tree/master/mingw-w64-python-pywin32 are graciously keeping an updated set of patches to install pywin32 for MingGW/msys2.

We’d suggest installing from https://packages.msys2.org/base/mingw-w64-python-pywin32 pacman -S mingw-w64-python-pywin32.

We’re open to seeing these patches be upstreamed in pywin32 if they can be tested automatically on the CI.

Running as a Windows Service

To run as a service, you probably want to install pywin32 globally from an elevated
command prompt — see above.

You also need to ensure Python is installed in a location where the user running
the service has access to the installation and is able to load pywintypesXX.dll and pythonXX.dll.
In particular, the LocalSystem account typically will not have access to your local %USER% directory structure.

Troubleshooting

If you encounter any problems when upgrading like the following:

The specified procedure could not be found
Entry-point not found

It usually means one of 2 things:

  • You’ve upgraded an install where the post-install script was previously run.
    So you should run it again:

    python -m pywin32_postinstall -install
    

    or (shorter but you don’t have control over which python environment is used)

    pywin32_postinstall -install
    

    This will make some small attempts to cleanup older conflicting installs.

  • There are other pywin32 DLLs installed in your system,
    but in a different location than the new ones. This sometimes happens in environments that
    come with pywin32 pre-shipped (eg, anaconda?).

    The possible solutions here are:

    • Run the «post_install» script documented above.
    • Otherwise, find and remove all other copies of pywintypesXX.dll and pythoncomXX.dll
      (where XX is the Python version — eg, «39»)

Building from source

Install Visual Studio 2019 (later probably works, but options might be different),
follow the instructions in Build environment
for the version you install.

Then follow the Build instructions for the build itself (including ARM64 cross-compilation).

Release process

The following steps are performed when making a new release — this is mainly
to form a checklist so @mhammond doesn’t forget what to do :)

Since build 307 the release process is based on the artifacts created by Github actions.

  • Ensure CHANGES.txt has everything worth noting. Update the header to reflect
    the about-to-be released build and date, commit it.

  • Update setup.py with the new build number. Update CHANGES.txt to have a new heading
    section for the next unreleased version. (ie, a new, empty «Coming in build XXX, as yet unreleased»
    section)

  • Push these changes to github, wait for the actions to complete, then
    download the artifacts from that run.

  • Upload .whl artifacts to pypi — we do this before pushing the tag because they might be
    rejected for an invalid README.md. Done via py -3.? -m twine upload dist/*XXX*.whl.

  • Create a new git tag for the release.

  • Update setup.py with the new build number + «.1» (eg, 123.1), to ensure
    future test builds aren’t mistaken for the real release.

  • Make sure everything is pushed to github, including the tag (ie,
    git push --tags)

  • Send mail to python-win32

Older Manual Release Process

This is the old process used when a local dev environment was used to create
the builds. Build 306 was the last released with this process.

  • Ensure CHANGES.txt has everything worth noting. Update the header to reflect
    the about-to-be released build and date, commit it.

  • Update setup.py with the new build number.

  • Execute make_all.bat, wait forever, test the artifacts.

  • Upload .whl artifacts to pypi — we do this before pushing the tag because they might be
    rejected for an invalid README.md. Done via py -3.? -m twine upload dist/*XXX*.whl.

  • Commit setup.py (so the new build number is in the repo), create a new git tag

  • Upload the .exe installers to github.

  • Update setup.py with the new build number + «.1» (eg, 123.1), to ensure
    future test builds aren’t mistaken for the real release.

  • Make sure everything is pushed to github, including the tag (ie,
    git push --tags)

  • Send mail to python-win32

Overview¶

pywin32 only supports the Windows operating system 😉 and Python ≥ 3.6. Release 228 is the last to support Python 2. Binary releases are deprecated.

Todo

  • Add commentary about using Virtual Environments.

  • Add commentary about whether pywin32 works from WSL2.

PyPI¶

Install pywin32 from PyPI with pip from the Command Prompt or Windows PowerShell:

❯ python -m pip install --upgrade pywin32

If you encounter any problems when upgrading (e.g., “module not found” errors), execute:

❯ python Scripts/pywin32_postinstall.py -install

This will make some small attempts to cleanup older conflicting installs.

Note

To use pywin32 for system-wide features, such as registering COM objects or implementing Windows Services, run pywin32_postinstall.py from an elevated command prompt (i.e., “Run as Administrator”).

Build from source¶

Building from source requires Visual Studio and the Windows SDK. Some free compilers probably work but have not been tested. Let me know your experiences!

Install using setup.py:

❯ python setup.py install

or

You can run setup.py without any arguments to see specific information about dependencies. A vanilla MSVC installation should be able to build most extensions and list any extensions that could not be built due to missing libraries. If the build actually fails with your configuration, please open an issue.

Pre-release builds¶

For unreleased changes, download builds made by GitHub Actions:

  • Choose any “workflow” from the main branch

  • Download its “artifacts”

Binary releases¶

Deprecated since version 305: Install from PyPI instead. See Release 305 notes.

pywin32 traditionally offered pywin32.exe files for installation. This is going to stop soon.

Support for building pywin32.exe installers was removed from setuptools. At some point in the future they cannot be provided.

While they are still provided, find them on GitHub.

Run as a Windows Service¶

Modern Python installers do not, by default, install Python in a way that is suitable for running as a service, particularly for other users.

Ensure Python is installed in a location where the user running the service has access to the installation and is able to load pywintypesXX.dll and pythonXX.dll.

Manually copy pythonservice.exe from the site-packageswin32 directory to the same place as these DLL files.

Troubleshooting¶

A very common report is that people install pywin32, but many imports fail with errors similar to “The specified procedure could not be found” or “Entry-point not found”.

In almost all cases, this tends to mean there are other pywin32 DLLs installed in your system but in a different location than the new ones. This sometimes happens in environments that ship with pywin32 (e.g., Anaconda).

The possible solutions are:

  • Run the pywin32_postinstall.py script documented above.

  • Find and remove all other copies of pywintypesXX.dll and pythoncomXX.dll (where XX is the Python version (e.g., 39 for Python 3.9).

  • pywin32 is an open source python library that can be used to access Windows COM.
    Access to COM means that we can control and modify windows programs using python.
    This helps us to implement almost any thing a windows program can do, like working with excel data, sending outlook email,
    track session lock/unlock events, mouse pointer data, screen information, etc.

    pywin32 is a huge library and forms the foundation of many other libraries.
    For example, any python GUI libraries that supports Windows OS implements pywin32,
    as this already has components related to windows GUI.

    This article lists some of the most important modules of pywin32 with sample usages.

    Complete documentation here.

  • Contents

    • Install pywin32
    • To check if pywin32 installed successfully
    • Important pywin32 modules
    • win32clipboard
    • win32api
    • odbc
    • timer
    • win32evtlog
    • win32file
    • win32gui
    • win32ts
    • pywintypes

  1. Install pywin32

    Download and install the latest version of python from Python Website.

    Set up virtual environment also if needed.

    Install pywin32 using the command: pip install pywin32

  2. To check if pywin32 installed successfully

    Type command pip freeze
    Should give an output like:

    pywin32==302
    

  3. Important pywin32 modules

    pywin32 has many sub modules, which handles specific functions.
    When working with pywin32 in our python code, we will be importing these modules mostly, rather than
    importing pywin32. Below are list of some of the most used modules and its functionalities.

    Module Name Description
    win32 clipboard Access and modify clipboard data.
    win32api Enables implementing functions like shutdown or restart, log off, beep from speaker, copy file, delete file, search file
    get computer name, current user name, local time, windows OS details etc.
    odbc To manage an odbc connection
    timer Start a timer to execute a function. Stop timer.
    win32evtlog Actions like retrieving and reading through a list of events, clearing event logs, backing it up, etc
    win32file Create directories, create/copy/ move/delete files, get/set filename, get file size, read/write strings to file, etc
    win32gui Working with windows GUI like, creating and modifying a GUI window, dialog boxes, writing text to window,
    creating images in window, draw shapes like, ellipse, rectangle, polygons, lines, etc
    win32ts Actions like, listing all the sessions in a server, get information about a session, logging off a session, etc
    pywintypes Create GUID, time object etc.
  4. win32clipboard samples

    Helps to work with clipboard data.

    import win32clipboard as w
    print("Number of formats currently on clipboard : ", w.CountClipboardFormats())#'Should have some copied data before executing this line'
    w.OpenClipboard(None)
    str = w.GetClipboardData(1)
    print("Clipboard data : ", str)
    w.SetClipboardText("New data in clipboard", 1)
    str = w.GetClipboardData(1)
    print("New clipboard data : ", str)
    print("Empty clipboard : ", w.EmptyClipboard())
    #str = w.GetClipboardData(1)#'Will throw an error because clipboard emptied - Specified clipboard format is not available.'
    

  5. win32api samples

    Enables implementing functions like shutdown or restart, log off, beep from speaker, copy file, delete file, search file
    get computer name, current user name, local time, windows os details etc.

    import win32api as w
    str = w.Beep(100, 1000)#'Frequency and duration in ms'
    w.CopyFile('src_file_name', 'dest_file_name', 0)#'Provide right path for it to work'
    w.DeleteFile('file_name')
    w.ExitWindows(0, 0)#'Log off current user'
    w.FindFiles('srchkey')#'Keyword should be a file or directory name. Wild cards * and ? allowed'
    w.FindExecutable(filename, dir)#'Retrieves details of exe associated with file specified'
    w.GetUserName()#'Current user name'
    w.GetLocalTime()
    w.GetSystemInfo()
    w.GetTickCount()#'Milliseconds since start of the system'
    w.mouse_event(0, 10, 200, 0, 0)#'Simulate mouse event'
    

  6. odbc Samples

    To list out all the ODBC data sources available, use below code. Will return None, if nothing is available.

    import odbc
    print(odbc.SQLDataSources(1))
    

  7. timer samples

    Start a timer to execute a function. Stop timer.

    import timer as t
    
    def func(timer_id, time):
        print('Timer function called every second')
        t.kill_timer(id)
    
    id = t.set_timer(1, func)
    print(id)
    

  8. win32evtlog samples

    Read through windows event logs of the specified server, clear it, backup, etc.

    import win32evtlog as w
    
    hdle = w.OpenEventLog(None,'Information')#'Server name and log name'
    flags = w.EVENTLOG_SEQUENTIAL_READ | w.EVENTLOG_BACKWARDS_READ
    ev=w.ReadEventLog(hdle,flags,0)
    print (ev)
    ev=w.CloseEventLog(hdle)
    

  9. win32file samples

    Create directories, create/copy/move/delete files, get/set filename, get file size, read/write strings to file, etc.

    import win32file as w
    
    w.CreateDirectory('New Dir', None)
    hdle = w.CreateFile('NewFile.txt', w.GENERIC_READ, 0, None, w.CREATE_NEW, 0, None)
    print(w.GetFileSize(hdle))
    print(w.ReadFile(hdle, 1000, None))
    #w.WriteFile(hdle, 'New Text', None)#'While creating file use w.GENERIC_WRITE for this to work'
    hdle.close()
    w.DeleteFile('NewFile.txt')
    

  10. win32gui samples

    Working with windows GUI like, creating and modifying a GUI window, dialog boxes, writing text to window,
    creating images in window, draw shapes like, ellipse, rectangle, polygons, lines, etc.
    This is a big topic. Below example just shows creating a window with a specified size.

    import win32api as api
    import win32con as con
    import win32gui as gui
    import win32ts as ts
    
    cname = "Test"
    hndle = api.GetModuleHandle(None)
    wc = gui.WNDCLASS()
    wc.hInstance = hndle
    wc.lpszClassName = cname
    cl = gui.RegisterClass(wc)
    s = con.WS_OVERLAPPEDWINDOW
    w = gui.CreateWindow(cl, cname, s, 100, 100, 500, 500, 0, 0, hndle, None)
    gui.UpdateWindow(w)
    gui.ShowWindow(w, con.SW_SHOW)
    ts.WTSRegisterSessionNotification(w, ts.NOTIFY_FOR_ALL_SESSIONS)
    
    if __name__ == '__main__':
        gui.PumpMessages()
    

  11. win32ts

    Actions like, listing all the sessions in a server, get information about a session, logging off a session, etc.
    Refer sample application
    Sedentary Reminder
    for usage details.

  12. pywintypes samples

    Create GUID, time object etc.

    import pywintypes
    print("New GUID : ", pywintypes.CreateGuid())
    print("Check Unicode : ", pywintypes.IsTextUnicode("1", 1))#Result is non zero if test passes
    print("New Time : ", pywintypes.Time(1000000000))
    

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Завершить все процессы пользователя windows
  • Мощный китайский планшет на windows
  • Не открываются фото на компьютере что делать windows
  • Включить гостевой сетевой доступ windows 10
  • Тема для windows infiniti