Python как установить win32com

Как установить библиотеку Win32com Python

Я пытаюсь установить модуль win32com. Я знаю, что должен загрузить расширение Python для Windows, но оно не работает. После того, как я установил Python для Windows и попытался import win32com.client , я получил следующее сообщение об ошибке:

>>> import win32com.client Traceback (most recent call last): File "", line 1, in import win32com.client File "C:\Python27\lib\site-packages\win32com\__init__.py", line 5, in import win32api, sys, os ImportError: No module named win32api 

Попытка google для получения справки о том, как установить win32api для Python, также не помогает; Я только что снова обратился к расширениям Python для Windows.

4 ответа 4

Проверьте sys.path, чтобы убедиться, что каталог, в котором установлен модуль, находится там, в противном случае вы должны добавить его (окна Google PYTHONPATH для некоторой помощи с этим.)

  1. Запустите командную строку с правами администратора.
  2. python -m pip install pywin32
  3. C:\Program Files\Stackless36\Scripts>python pywin32_postinstall.py -install
  4. python C:\code\Python\speech\speak.py

Где speak.py состоит из этого текста:

import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") speaker.Speak("It works, bitches.") 

Отлично работает на Python 3.6.4 Stackless 3.1b3 060516 (v3.6.4-slp:9557b2e530, 21 декабря 2017, 15:23:10) [MSC v.1900 64 bit (AMD64)] на win32. Ванильный CPython висит здесь:

C:\Users\C\AppData\Local\Programs\Python\Python36-32>python.exe Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'win32com' >>> exit() C:\Users\C\AppData\Local\Programs\Python\Python36-32>python.exe -m pip install pywin32 Collecting pywin32 Cache entry deserialization failed, entry ignored Downloading https://files.pythonhosted.org/packages/d4/2d/b927e61c4a2b0aaaab72c8cb97cf748c319c399d804293164b0c43380d5f/pywin32-223-cp36-cp36m-win32.whl (8.3MB) 100% |████████████████████████████████| 8.3MB 50kB/s Installing collected packages: pywin32 Successfully installed pywin32-223 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. 

Источник

Читайте также:  Html javascript style display

How to install win32com.client in Python

This tutorial will see how to install win32com.client in Python. Using this you can access the windows 32 APIs from Python.

From python version 3.9 onwards this library is preinstalled with the python package. And for other versions, it is not. So before installing check the python version using this command.

Note: Also try to import the library in some Python code to see if it’s giving any ImportError. If it’s not it means it’s already installed in your Python version.

Install pywin32 using pip

Now open the command prompt on your machine and type the following command to install pywin32 using pip.

It will download and install the package on your machine.

After successful installation, try to use the library in Python code to ensure that the package is working appropriately.
Example:

install win32com.client in Python

After execution, it returned 1 which means the code has been executed successfully without any errors.

Install win32api using conda

You can also install the win32api module using conda , which is the package manager for the Anaconda distribution of Python. To install the win32api module using conda , type the following command in the command prompt:

conda install -c anaconda pywin32
Once the win32api module is installed, you can import it into your Python code and use its functions. For example:

import win32api # Get the current working directory cwd = win32api.GetCurrentDirectory() print(cwd)

Источник

How to install the win32com python library

I am trying to install the win32com module. I know I should download the Python for Windows extension, but it does not work. After I have installed Python for Windows and try import win32com.client , I get the following error message:

>>> import win32com.client Traceback (most recent call last): File "", line 1, in import win32com.client File "C:\Python27\lib\site-packages\win32com\__init__.py", line 5, in import win32api, sys, os ImportError: No module named win32api 

Trying to google for help on how to install win32api for Python does not help either; I am just referred to the Python for Windows extensions again.

Did you install the right binary of Python for Windows extensions for your version of Python? For example, if you install 64-bit Python, then install the 32-bit extensions, the pure-Python modules (like win32con ) will import, but the C-extension modules (like win32api ) will not; if you install Python 2.6, then install the extensions for 2.7, they may import but crash later; etc.

4 Answers 4

  1. Start a command line with admin rights.
  2. python -m pip install pywin32
  3. C:\Program Files\Stackless36\Scripts>python pywin32_postinstall.py -install The path C:\Program Files\Stackless36\ should be replaced with the path at which your Python version is installed.
  4. Test (admin rights optional) using python -c «import win32com» or python speak.py where speak.py consists of this text:
import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") speaker.Speak("It works. Hoorah!") 

Working fine on Python 3.6.4 Stackless 3.1b3 060516 (v3.6.4-slp:9557b2e530, Dec 21 2017, 15:23:10) [MSC v.1900 64 bit (AMD64)] on win32. Vanilla CPython hangs out here:

C:\Users\C\AppData\Local\Programs\Python\Python36-32>python.exe Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'win32com' >>> exit() C:\Users\C\AppData\Local\Programs\Python\Python36-32>python.exe -m pip install pywin32 Collecting pywin32 Cache entry deserialization failed, entry ignored Downloading https://files.pythonhosted.org/packages/d4/2d/b927e61c4a2b0aaaab72c8cb97cf748c319c399d804293164b0c43380d5f/pywin32-223-cp36-cp36m-win32.whl (8.3MB) 100% |████████████████████████████████| 8.3MB 50kB/s Installing collected packages: pywin32 Successfully installed pywin32-223 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. 

Источник

blogBlog

How to use Python with a COM library like HttpWatch

calendar

March 22, 2019 in Automation , HttpWatch , Python

We occasionally get asked whether the HttpWatch automation library can be used with Python. The simple is yes – Python can be used just like any other programming language that supports COM on Windows. This blog post describes how to use the HttpWatch interface but the same approach can be used to access other COM components from Python.

Although, it’s possible to use simple, named based look-ups in COM (known as late binding) it’s better to use early binding as it has some key advantages:

  • Better performance as COM methods don’t have to queried by name before execution
  • It makes use of Python static typing – allowing IDEs (such as PyCharm) to provide intellisense and to detect syntax errors

The following steps show you how to build a static typed Python client for any COM library with example code for the HttpWatch automation library.

1. Prerequisites

Before starting to program in Python you’ll need to do the following:

  1. Install the latest version of Python
  2. Use an existing IDE or install one like PyCharm
  3. Create a directory or project for your Python code. In PyCharm configure the project to use the system Python interpreter rather than a per-project virtual environment. This makes it simpler to use the win32com module (see next section)

2. Install the Python pywin32 module

Python doesn’t have built-in in COM support so you’ll need to install the pywin32 module by manually running several commands.

Start a command prompt using an account with local admin rights. On Windows 10 you can right click on the Windows icon and select ‘Command Prompt (Admin)’

Run the following command to add pywin32 to Python:

python -m pip install pywin32

Then locate the post install script pywin32_postinstall.py. It should be in directory like this:

C:\Users\username\AppData\Local\Programs\Python\Python37\Scripts

Change to that directory and run this command to complete the setup:

C:\Users\username\AppData\Local\Programs\Python\Python37\Scripts>python pywin32_postinstall.py -install 

3. Generate the Python bindings for the COM library

After installing pywin32 use the makepy utility to generate a python binding file for the COM library you want to use. You can do this by creating and running the following Python file:

import sys from win32com.client import makepy outputFile = r"c:\mypythonclient\httpwatch_automation.py" comTypeLibraryOrDLL = r"C:\Program Files (x86)\HttpWatch\httpwatchprox64.dll" sys.argv = ["makepy", "-o", outputFile, comTypeLibraryOrDLL] makepy.main ()

Set the outputFile variable to use the directory where you will create your Python client code. The comTypeLibraryOrDLLvariable should be set to the location of the Type Library (.tlb) or Dynamic Link Library (.dll) that implements the target COM library

The code above shows the values to use for HttpWatch but you can skip this step if you prefer and directly download the Python binding file that we generated with Python 3.7 and HttpWatch 11.1:

4. Import win32com.client and the Python bindings file

You’ll need two import statements in your Python code. The first allows win32com.client to be used for creating instances of COM classes and the second imports the classes and interfaces found in the target COM library:

import win32com.client import httpwatch_automation as HttpWatch

The second import uses the base name of the Python binding file generated in step# 3 and wraps the types in the specified namespace (i.e. HttpWatch in this case). The binding file will be located automatically if it exists in the same directory as your Python code.

5. Use static binding to create an instance of the COM class

Python variables are dynamically typed by default. This means that they take on the type of whatever is assigned into them. You can change to using static typing by specifying the type after the variable declaration. In the code below we used HttpWatch.IController as that’s the interface type for the initial Controller COM class used by HttpWatch.

An instance of the HttpWatch Controller class is created by supplying its CLSID value to the win32com.client Dispatch method:

controller: HttpWatch.IController = win32com.client.Dispatch(HttpWatch.Controller.CLSID)

Once you’ve done this the IDE can provide intellisense when you write code using that variable:

You don’t even need to specify the types for other variables that are used to hold values derived from the initial interface. The IDE can deduce their type by looking at the information in the Python binding file.

For example, the plugin variable is statically typed as the Plugin interface because the IDE knows that the New method returns a Plugin interface:

6. Write the rest of your code!

After setting up the type information you can then write the rest of the code required to interact with the COM library. Here’s an example that uses HttpWatch to open a page in Chrome and display some simple statistics about the network traffic:

import win32com.client import httpwatch_automation as HttpWatch controller: HttpWatch.IController = win32com.client.Dispatch(HttpWatch.Controller.CLSID) # Create a new instance of HttpWatch in Chrome # (Change to controller.IE.New() to open Internet Explorer instead) plugin = controller.Chrome.New() # Start Recording HTTP/HTTPS traffic plugin.Log.EnableFilter(False) plugin.Record() # Goto to the URL and wait for the page to be loaded url = "https://www.httpwatch.com/download/" plugin.GotoURL(url) print("\nWaiting for page to finish loading. ") controller.Wait(plugin, -1) print("Page loaing complete") # Stop recording HTTP/HTTPS plugin.Stop() if plugin.Log.Pages.Count != 0: print("\nPage Title: '" + plugin.Log.Pages(0).Title + "'") # Display summary statistics for page summary = plugin.Log.Pages(0).Entries.Summary print( "Total time to load page (secs): " + str(summary.Time)) print( "Number of bytes received on network: " + str(summary.BytesReceived)) print( "HTTP compression saving (bytes): " + str(summary.CompressionSavedBytes)) print( "Number of round trips: " + str(summary.RoundTrips)) print( "Number of errors: " + str(summary.Errors.Count)) # Close down Chrome plugin.CloseBrowser()

Источник

Оцените статью