Re: [python-win32] PyWin32 Advanced Options

2024-01-19 Thread Steven Manross
Your mileage may vary, but while using setprinter.exe for a similar task (many 
years ago) I found that the different trays can sometimes be large values like 
260…

Your best bet might be to set the tray manually in the UI, and then try to look 
at those values via something like setprinter.exe

The values from setprinter.exe show dmDefaultSource instead of DefaultSource, 
but it’s all the same

If you need setprinter.exe it should be easily downloadable from sourceforge.

HTH

Steven
From: python-win32  On 
Behalf Of Michael Litvin
Sent: Thursday, January 18, 2024 1:07 PM
To: python-win32@python.org
Subject: [python-win32] PyWin32 Advanced Options

Hello,

I am trying to print from python using the bypass tray on my printer, but I 
cannot seem to get it working and it always prints from tray 1.

Here is my code:
image = Image.open(file_path)
printer_handle = win32print.OpenPrinter(printer_name)
p_info = win32print.GetPrinter(printer_handle, 2)
devmode = p_info["pDevMode"]
devmode.PaperWidth = 3550
devmode.PaperLength = 8510
devmode.DefaultSource = 4
# bins = win32print.DeviceCapabilities(printer_name, devmode.DeviceName, 
win32con.DC_BINS)
# bin_names = win32print.DeviceCapabilities(printer_name, 
devmode.DeviceName, win32con.DC_BINNAMES)
# for bin, bin_name in zip(bins, bin_names):
# print(f"Bin number: {bin}, Bin name: {bin_name}")
hDC = win32ui.CreateDC()
hDC.CreatePrinterDC(printer_name)
hDC.StartDoc(file_path)
hDC.StartPage()
dib = ImageWin.Dib(image)
dib.draw(hDC.GetHandleOutput(), (0, 0, image.size[0],image.size[1]))
hDC.EndPage()
hDC.EndDoc()
hDC.DeleteDC()

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Uninstallation Command Required

2023-09-20 Thread Steven Manross
As well, you can look in the windows registry in the Uninstall key (but need to 
find the specific key for your python installer)

# this registry key is for version 3.9.12 (but the only thing that would change 
on other versions would be the final key name: the GUID)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{33807E24-D0B9-45A0-A48D-51A432CD27E8}

Once you have found the registry key for Python, look at the UninstallString 
value:

Which is this for one of my PCs:
MsiExec.exe /I{33807E24-D0B9-45A0-A48D-51A432CD27E8}

From there, you could add a /q or /quiet for a quiet uninstall…

For more help with the windows MSIEXEC util, run msiexec /? And it will give 
you a lot of help/switches

I hope that between these 2 answers, we have given you everything you need.

Steven
From: python-win32  On 
Behalf Of Bob Kline
Sent: Wednesday, September 20, 2023 12:32 PM
To: Sujith R 
Cc: python-win32@python.org
Subject: Re: [python-win32] Uninstallation Command Required

Depends on how it was installed. If you used the installer from 
python.org, it might look like this:

python-3.11.1-amd64.exe /uninstall /quiet > uninstall.log

(Adjust the name of the executable to match the version you installed.)

If you used some other distribution (for example, from ActiveState) follow the 
instructions provided by that distributor.

On Wed, Sep 20, 2023 at 3:19 PM Sujith R 
mailto:jerinsujit...@gmail.com>> wrote:
Hi Team,

I need to uninstall python via windows command prompt. I tried lots of various 
commands but it’s not worked well. Can you please help me to solve this issue.

SUMMARY: Need a proper uninstall command for windows

Thanks in advance.
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


--
Bob Kline
https://www.rksystems.com
mailto:bkl...@rksystems.com
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Question win32com.client.Dispatch

2023-07-11 Thread Steven Manross
When building your “AutoCad.Application” object, it looks like 2007 is the 
default object…

In your computer’s registry directly under HKEY_CLASSES_ROOT you should be able 
to find a Key (FOLDER icon) that matches that name…  as well, IF AutoCAD has 
different versions installed , you should be able to see 
“AutoCad.Application.###” as well, which should be the COM Object name for 
the specific version you are looking for.

While I don’t have AutoCad installed, Microsoft Excel is an application that 
goes about this the same way…

If I had 2+ versions of Excel installed, I would send “Excel.Application.16” to 
work with for my currently installed version of Office 2019.

I hope this helps.

Steven
From: python-win32  On 
Behalf Of Mateo Gomez Montoya
Sent: Tuesday, July 11, 2023 10:20 AM
To: python-win32@python.org
Subject: [python-win32] Question win32com.client.Dispatch

Hello,

I'm trying to use the command of 
win32com.client.Dispatch("AutoCAD.Application") and on the computer that I'm 
working with there are two versions of AutoCAD one from 2007 and another from 
2021. I want to use a program that I created with the most recent version but 
when I run my code it automatically opens up AutoCAD2007. How can I create a 
dispatch that will run the most recent version of AutoCAD no matter the  
computer?

P.S I don't want to uninstall the 2007 version since it runs some of my older 
programs.

Thank you
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Setting Focus Assist Mode via COM

2023-05-31 Thread Steven Manross
Interfaces are definitely different and cannot be used with IDispatch, etc.

Someone with more experience might be able to direct you to something, but as 
far as I know, that’s reserved for C++ (or likely ctypes in python…  but that’s 
on the fringe of what I’m capable of helping with – and completely outside the 
scope of the pywin32 module).

But to make it more clear..  ctypes is how python can call things like that C++ 
code, but my one endeavor into that space was a VERY long and frustrating road 
as making sure that all the prerequisite data structures were created (and 
defined correctly) was a daunting task, and someone ended up figuring it out 
for me – as I was totally missing different structures that needed to be 
defined (it was for some data from Terminal Server that is not publicly 
supported – but totally capable of being read from Windows).

HTH

Steven
From: python-win32  On 
Behalf Of name zero via python-win32
Sent: Tuesday, May 30, 2023 10:32 PM
To: python-win32@python.org
Subject: Re: [python-win32] Setting Focus Assist Mode via COM

Hi,

thanks for explaining the issue with clsids.

The "application" is basically part of MS Windows. Talking to it via COM is 
100% possible, as the C++ code (that is part of the GitHub-Gist) 
demonstrates<https://gist.github.com/riverar/085d98ffb1343e92225a10817109b2e3#file-quiethours_example-cpp-L23>.
 It just doesn't work with pywin32.

When I look for "6bff4732-81ec-4ffb-ae67-b6c1bc29631f" in the Windows registry, 
I only find an entry in "HKEY_CLASSES_ROOT\Interface" (there is no entry in 
HKEY_CLASSES_ROOT\clsid) with a default value of  "IQuietHoursSettings". But 
win32com.client.Dispatch('IQuietHoursSettings') fails with the error message 
"Invalid class string".

Best regards!


On Tuesday, May 30, 2023 at 11:41:25 PM GMT+2, Steven Manross 
mailto:ste...@manross.net>> wrote:



While I haven’t worked on exactly what you are working on:



I’d first verify suggest that the application that installs this class needs to 
be installed on the PC you are trying to create the automation from, because 
“Class not Registered” isn’t a python error, and it talks more directly to the 
fact that the appropriate class from the software you are trying to automate 
isn’t on the computer you are running python from: so either you have the wrong 
CLSID or are doing something else wrong (missing software???).



Classes are listed in the registry here:



HKEY_CLASSES_ROOT\clsid\{6bff4732-81ec-4ffb-ae67-b6c1bc29631f}

… and your CLSID would need to exist (as installed from whatever software you 
are trying to automate) prior to python being able to automate it.



Here is an example that should work on your system…



ms_dict = win32com.client.Dispatch('Scripting.Dictionary')



… because the scripting dictionary object class is installed in just about 
every Windows OS since pre-WindowsXP



I hope this helps.  Enjoy your day.



Steven

From: python-win32 
mailto:python-win32-bounces+steven=manross@python.org>>
 On Behalf Of name zero via python-win32
Sent: Monday, May 29, 2023 6:02 AM
To: python-win32@python.org<mailto:python-win32@python.org>
Subject: [python-win32] Setting Focus Assist Mode via COM



Hi,



could someone help me out with first steps for how to set Focus Assist via COM, 
which https://gist.github.com/riverar/085d98ffb1343e92225a10817109b2e3 
demonstrates for a C++ code base? Something like



win32com.client.Dispatch('{6bff4732-81ec-4ffb-ae67-b6c1bc29631f}', 
clsctx=pythoncom.CLSCTX_LOCAL_SERVER)



fails with "pywintypes.com_error: (-2147221164, 'Class not registered', None, 
None)"



Thank you and best regards!
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Setting Focus Assist Mode via COM

2023-05-30 Thread Steven Manross
While I haven’t worked on exactly what you are working on:

I’d first verify suggest that the application that installs this class needs to 
be installed on the PC you are trying to create the automation from, because 
“Class not Registered” isn’t a python error, and it talks more directly to the 
fact that the appropriate class from the software you are trying to automate 
isn’t on the computer you are running python from: so either you have the wrong 
CLSID or are doing something else wrong (missing software???).

Classes are listed in the registry here:

HKEY_CLASSES_ROOT\clsid\{6bff4732-81ec-4ffb-ae67-b6c1bc29631f}

… and your CLSID would need to exist (as installed from whatever software you 
are trying to automate) prior to python being able to automate it.

Here is an example that should work on your system…

ms_dict = win32com.client.Dispatch('Scripting.Dictionary')

… because the scripting dictionary object class is installed in just about 
every Windows OS since pre-WindowsXP

I hope this helps.  Enjoy your day.

Steven
From: python-win32  On 
Behalf Of name zero via python-win32
Sent: Monday, May 29, 2023 6:02 AM
To: python-win32@python.org
Subject: [python-win32] Setting Focus Assist Mode via COM

Hi,

could someone help me out with first steps for how to set Focus Assist via COM, 
which https://gist.github.com/riverar/085d98ffb1343e92225a10817109b2e3 
demonstrates for a C++ code base? Something like

win32com.client.Dispatch('{6bff4732-81ec-4ffb-ae67-b6c1bc29631f}', 
clsctx=pythoncom.CLSCTX_LOCAL_SERVER)

fails with "pywintypes.com_error: (-2147221164, 'Class not registered', None, 
None)"

Thank you and best regards!
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] unknow solution

2023-05-30 Thread Steven Manross
While I’ve done word automation in the past, is it possible that there’s any 
issues with the word application installation itself?  Or maybe you might have 
multiple scripts trying to open/write files simultaneously?

As well, I might consider looking at task manager on your web server to see if 
there are a lot of processes for word that might create some sort of 
bottleneck, or concurrency issue.

I know when I am doing some selenium work with Google Chrome, sometimes it 
leaves a rogue Chrome process running, and as a result, the server gets bogged 
down and can’t do what it’s supposed to very well because of all the chrome 
processes left over from failed python script instances.

Typically the error you are seeing might point to a problem with some variable 
you believe should be an expected value, but in this case, it’s None, or 
another non-standard value…  Typically, I will log that kind of data from my 
classic asp web pages to understand the problem more.

In your case, I might start by writing the file name (self.ruta) to a log file 
in case it’s blank, or has special characters in it that could be causing 
issues.

I hope this helps.  The error messages you are seeing are quite generic, and 
reference a problem with rendering the webpage and not necessarily a python 
specific error.

Steven
From: python-win32  On 
Behalf Of Martín Trujillo Raddatz
Sent: Monday, May 29, 2023 12:05 PM
To: python-win32@python.org
Subject: [python-win32] unknow solution

i ve using the library for some time now without any trouble.. but a few 
days ago the script for a conversion in word from doc to pdf respond with this 
error sometimes, other works fine, the error is random, i cant figure out why 
occurs.

the error is:

Traceback (most recent call last):
  File 
"C:\inetpub\wwwroot\ruc2docs\venv\lib\site-packages\win32com\client\dynamic.py",
 line 81, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operación no disponible', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\inetpub\wwwroot\ruc2docs\r2d2documento.py", line 14, in __init__
self.save_as_('pdf')
  File "C:\inetpub\wwwroot\ruc2docs\r2d2documento.py", line 25, in save_as_
word = win32.gencache.EnsureDispatch('Word.Application')
  File 
"C:\inetpub\wwwroot\ruc2docs\venv\lib\site-packages\win32com\client\gencache.py",
 line 524, in EnsureDispatch
disp = win32com.client.Dispatch(prog_id)
  File 
"C:\inetpub\wwwroot\ruc2docs\venv\lib\site-packages\win32com\client\__init__.py",
 line 95, in Dispatch
dispatch, userName = 
dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File 
"C:\inetpub\wwwroot\ruc2docs\venv\lib\site-packages\win32com\client\dynamic.py",
 line 98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File 
"C:\inetpub\wwwroot\ruc2docs\venv\lib\site-packages\win32com\client\dynamic.py",
 line 83, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, 
pythoncom.IID_IDispatch)
pywintypes.com_error: (-2146959355, 'Error en la ejecución de servidor', None, 
None)

the code to execute the conversion is:

def save_as_(self, tipo):
import win32com.client as win32
from win32com.client import constants
# self.registrar_conversion()
word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(self.ruta, ReadOnly=True, 
AddToRecentFiles=False, Revert=True, Visible=False)
doc.Activate()
if tipo == 'pdf':
word.ActiveDocument.SaveAs(self.ruta[:-4] + '.pdf', 
FileFormat=constants.wdFormatPDF)
elif tipo == 'docx':
word.ActiveDocument.SaveAs(self.ruta[:-4] + '.doc', 
FileFormat=constants.wdFormatXMLDocument)
doc.Close(SaveChanges=constants.wdDoNotSaveChanges)
word.Quit()

Thank you!


Martín Trujillo Raddatz
Puerto Montt - Chile
Teléfono: +56 9 96427814

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] makepy.py "Some COM library"

2023-05-30 Thread Steven Manross
C:\Python39\Lib\site-packages\win32com\client>python -c "from 
win32com.client.gencache import EnsureDispatch; 
EnsureDispatch('ADODB.Connection.6.0');

That code seems to generate a directory in the correct path in both 3.9 and 3.11

C:\Python39\Lib\site-packages\win32com\gen_py\B691E011-1797-432E-907A-4D8C69339129x0x6x1
* With the files:
__init__.py
_Connection.py
Connection.py
ConnectionEvents.py

* Similar for 3.11 (base dir name is C:\Python311)

Also…  I’ve noticed (just now) that Python 3.9 makepy.py seems to put the 
constants file in the correct path…  and 3.11 doesn’t.

Test environment = Win2019 (Py3.11 – multiple systems) and Win10 (Py3.9 – one 
system)…  I should have some 3.10 systems here too in case that helps identify 
any issue(s)

HTH and let know if you want any more testing performed.  I’m always happy to 
help.

Steven
From: Mark Hammond 
Sent: Tuesday, May 30, 2023 11:01 AM
To: Steven Manross ; python-win32@python.org
Subject: Re: [python-win32] makepy.py "Some COM library"


Does something like `python -c "from win32com.client.gencache import 
EnsureDispatch; EnsureDispatch('ADODB.Connection.6.0');` work? That should 
generate directly into the expected output directory.

Mark
On 2023-05-30 1:44 p.m., Steven Manross wrote:
Command I ran:

C:\Python311\Lib\site-packages\win32com\client>python makepy.py 
"ADODB.Connection.6.0"

Output:
Generating to 
C:\Users\someuser\AppData\Local\Temp\13\gen_py\3.11\B691E011-1797-432E-907A-4D8C69339129x0x6x1.py
Building definitions from type library...
Generating...
Importing module

---

I am running the command above, and if I do this, my Classic ASP does not see 
the resulting B691E011-1797-432E-907A-4D8C69339129x0x6x1.py file because it 
saved the file in the user temp directory as opposed to in the site-packages 
directory structure.


  1.  When I installed Python, I told it to install the application for “All 
Users” (Default Directory = C:\Program Files\Python311 -- but I removed the 
Program Files portion for the installation)

Is there some way to make it save the file in the correct place for the python 
installation from the command line so I don’t have to move the files it 
generates?

Keep in mind that the files it generates seems to live in a 3.11 directory, but 
python seems to want it in:

C:\Python311\Lib\site-packages\win32com\gen_py\B691E011-1797-432E-907A-4D8C69339129x0x6x1.py
C:\Python311\Lib\site-packages\win32com\gen_py\dicts.dat
C:\Python311\Lib\site-packages\win32com\gen_py\__init__.py

I saw the -o parameter in the makepy.py script but if I use that, it doesn’t 
seem to build the dicts.dat or __init__.py files – which already exist (is that 
a problem?).

Please and thank you for any comments,
Steven



___

python-win32 mailing list

python-win32@python.org<mailto:python-win32@python.org>

https://mail.python.org/mailman/listinfo/python-win32
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


[python-win32] makepy.py "Some COM library"

2023-05-30 Thread Steven Manross
Command I ran:

C:\Python311\Lib\site-packages\win32com\client>python makepy.py 
"ADODB.Connection.6.0"

Output:
Generating to 
C:\Users\someuser\AppData\Local\Temp\13\gen_py\3.11\B691E011-1797-432E-907A-4D8C69339129x0x6x1.py
Building definitions from type library...
Generating...
Importing module

---

I am running the command above, and if I do this, my Classic ASP does not see 
the resulting B691E011-1797-432E-907A-4D8C69339129x0x6x1.py file because it 
saved the file in the user temp directory as opposed to in the site-packages 
directory structure.


  *   When I installed Python, I told it to install the application for "All 
Users" (Default Directory = C:\Program Files\Python311 -- but I removed the 
Program Files portion for the installation)

Is there some way to make it save the file in the correct place for the python 
installation from the command line so I don't have to move the files it 
generates?

Keep in mind that the files it generates seems to live in a 3.11 directory, but 
python seems to want it in:

C:\Python311\Lib\site-packages\win32com\gen_py\B691E011-1797-432E-907A-4D8C69339129x0x6x1.py
C:\Python311\Lib\site-packages\win32com\gen_py\dicts.dat
C:\Python311\Lib\site-packages\win32com\gen_py\__init__.py

I saw the -o parameter in the makepy.py script but if I use that, it doesn't 
seem to build the dicts.dat or __init__.py files - which already exist (is that 
a problem?).

Please and thank you for any comments,
Steven
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Win32: -2147418113, 'Catastrophic failure'

2023-05-23 Thread Steven Manross
And just to reiterate what Mark said, but also validate that this is the case 
from code:

You should be able to run this without issue… (and validate pywin32 works fine)

mydict = win32com.client.Dispatch("Scripting.Dictionary")

… since the “Scripting.Dictionary” COM class lives on every windows 
installation since Windows 2000 (or earlier).

Steven
From: python-win32  On 
Behalf Of Pranav S Pawar
Sent: Monday, May 22, 2023 8:05 AM
To: Mark Hammond ; python-win32@python.org
Subject: [python-win32] Win32: -2147418113, 'Catastrophic failure'

Hello Team,

My code was working fine from one week in jupyter notebook.
Today i just did a kernel restart in jupyter notebook and my code stopped 
working.

Not sure what happened after restart. Tried all options but not able to resolve.
So through to get help from here.

Basically i am trying to get erwin api through => 
win32com.client.Dispatch("erwin9.SCAPI")

but getting error.

Giving Code as well as error below.
Please advise what corrective action should be taken.
I have tried to upgrade pywin32 module but still same error.

Code:
import win32com.client
erwin = win32com.client.Dispatch("erwin9.SCAPI")
print('Connected')

Error:


com_error Traceback (most recent call last)

File C:\Python310\lib\site-packages\win32com\client\dynamic.py:84, in 
_GetGoodDispatch(IDispatch, clsctx)

 83 try:

---> 84 IDispatch = pythoncom.connect(IDispatch)

 85 except pythoncom.ole_error:



com_error: (-2147221021, 'Operation unavailable', None, None)



During handling of the above exception, another exception occurred:



com_error Traceback (most recent call last)

Input In [17], in ()

  1 import win32com.client

> 3 erwin = win32com.client.Dispatch("erwin9.SCAPI")

  5 print('Connected')



File C:\Python310\lib\site-packages\win32com\client\__init__.py:118, in 
Dispatch(dispatch, userName, resultCLSID, typeinfo, UnicodeToString, clsctx)

116 """Creates a Dispatch based COM object."""

117 assert UnicodeToString is None, "this is deprecated and will go away"

--> 118 dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, 
userName, clsctx)

119 return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, 
clsctx=clsctx)



File C:\Python310\lib\site-packages\win32com\client\dynamic.py:104, in 
_GetGoodDispatchAndUserName(IDispatch, userName, clsctx)

101 ## ??? else userName remains None ???

102 else:

103 userName = str(userName)

--> 104 return (_GetGoodDispatch(IDispatch, clsctx), userName)



File C:\Python310\lib\site-packages\win32com\client\dynamic.py:86, in 
_GetGoodDispatch(IDispatch, clsctx)

 84 IDispatch = pythoncom.connect(IDispatch)

 85 except pythoncom.ole_error:

---> 86 IDispatch = pythoncom.CoCreateInstance(

 87 IDispatch, None, clsctx, pythoncom.IID_IDispatch

 88 )

 89 else:

 90 # may already be a wrapped class.

 91 IDispatch = getattr(IDispatch, "_oleobj_", IDispatch)



com_error: (-2147418113, 'Catastrophic failure', None, None)

Thanks & Best Regards,

Pranav
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] GetNetworkConnections fails since a Windows update

2023-05-03 Thread Steven Manross
That happens here too in Win10/Win11 using your code.  It looks like Microsoft 
altered the COM object for you not to be able to do a GetNetwork or GetCategory 
on the connection object, but that seems odd since it basically renders the 
object pointless.

P.S. some powershell code doesn't seem to be able to access the GetNetwork 
function either.

$networkListManager = 
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))
$connections = $networkListManager.GetNetworkConnections()

$connections |foreach {
$_.GetNetwork()
}

Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))
At line:2 char:5
+ $_.GetNetwork()
+ ~~~
+ CategoryInfo  : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Steven
-Original Message-
From: python-win32  On 
Behalf Of cwa...@gmail.com
Sent: Wednesday, May 3, 2023 7:00 AM
To: python-win32@python.org
Subject: [python-win32] GetNetworkConnections fails since a Windows update

Hello.

After a recent update on Windows 10, I not able to tell exactly which, I've a 
strange behavior on a program that works fine since 2015 on thousands of 
machines...



* With this code :

def networks_private():
 NETWORK_CATEGORIES = {1: "PRIVATE",0: "PUBLIC", 2: "DOMAIN"}
 m = win32com.client.Dispatch("{DCB00C01-570F-4A9B-8D69-199FDBA5723B}")
 more = 1
 pos = 1
 connections = m.GetNetworkConnections()
 while more:
 connection, more = connections.Next(pos)
 if connection:
 network = connection.GetNetwork()
 category = network.GetCategory()
 try:
 log('switching network interface in private mode')
 network.SetCategory(1)
 except:
 log("error switching network interface in private mode")
 pos += 1



* I get this error :

Traceback (most recent call last):
[...]
File "Frame1.pyo", line 163, in _init_
File "fonctions.pyo", line 201, in networks_private File 
"win32com\client\dynamic.pyo", line 522, ingetattr_
AttributeError: Next.GetNetwork



Regards, thanks.

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Accessing Documentation Through Command Prompt / Help File

2023-04-10 Thread Steven Manross
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-keybd_event

Personally, I’ve been using pyautogui a lot to do mostly mouse input (but it 
handles keyboard operations too)…

It seems that there isn’t a lot of MSDN documentation from Microsoft on this 
subject though.

Steven
From: python-win32  On 
Behalf Of Tommy Weber
Sent: Sunday, April 9, 2023 10:17 AM
To: python-win32@python.org
Subject: [python-win32] Accessing Documentation Through Command Prompt / Help 
File

Hello all,

First off thank you to the creators of this project! It seems incredibly useful.

Is there a more thorough version of the documentation than the online help 
version and if so how can I access it? I tried looking for a help file in the 
“.venv\Lib” path where it is installed but had no luck. I found plenty of Demo 
files though.

The online documentation seems very helpful although it is lacking in details. 
For instance, in the link below it specifies the dwFlags but then does not 
mention the flag options. Is there another place I could find this information?
https://mhammond.github.io/pywin32/win32api__keybd_event_meth.html
dwFlags=0 : DWORD
Flags specifying various function options

Please note my Python is rusty. I am used to PowerShell.

Feedback would be greatly appreciated!

Kind regards,
Tom
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Pywin32 Windows Service not responding

2023-03-25 Thread Steven Manross
Something seems to be stripping your code at about 40-50 characters and it 
seems like we are missing the right half of your code.

Example:

_svc_description_ = 'This is a sample Python Wind

Steven
From: python-win32  On 
Behalf Of jeremy.farmer1206 via python-win32
Sent: Friday, March 24, 2023 1:26 PM
To: python-win32@python.org
Subject: [python-win32] Pywin32 Windows Service not responding

Hi, I am looking for some assistance with utilizing pywin32 in order to create 
a Windows Service.

I've tried to create as bare-bones of an application as I could inheriting from 
win32serviceutil.ServiceFramework

import traceback
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import time
import os
import sys

class MyService(win32serviceutil.ServiceFramework):
_svc_name_ = 'MyPythonService'
_svc_display_name_ = 'My Python Service'
_svc_description_ = 'This is a sample Python Wind

def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(se
self.hWaitStop = win32event.CreateEvent(None,
socket.setdefaulttimeout(60)
self.is_alive = True
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE
win32event.SetEvent(self.hWaitStop)
self.is_alive = False

def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE
self.ReportServiceStatus(win32service.SERVICE
# win32event.WaitForSingleObject(self.hWaitSt
try:
servicemanager.LogMsg(servicemanager.EVEN
PYS_SERVICE_STARTED, (self._svc_name_, ''))
self.main()
except Exception as ex:
servicemanager.LogErrorMsg("Exception in
eback.format_exc()))
raise

def main(self):
while self.is_alive:
with open('test.txt', 'a') as f:
f.write('Service loop...')
time.sleep(2)

if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MyService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(MyService)


I've installed it via opening an admin command prompt and running

python main.py install

It installs successfully but if I attempt to run it, I get

[cid:image001.png@01D95F42.26DA6EF0]

Or

>python main.py start
Starting service MyPythonService
Error starting service: The service did not respond to the start or control 
request in a timely fashion.

debugging seems to work, or at least does not give any errors

python main.py debug
Debugging service MyPythonService - press Ctrl+C to stop.
Info 0x40001002 - The MyPythonService service has started.

I believe my pywin32 is fully up to date

python -m pip install --upgrade pywin32
Requirement already satisfied: pywin32 in 
c:\users\jerem\appdata\local\programs\python\python311\lib\site-packages (305)

Misc

python --version
Python 3.11.2

[cid:834fd2a@proton.me]

Any assistance is very much appreciated!
Sent with Proton Mail secure email.
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] How to add citations to a word document

2023-03-17 Thread Steven Manross
A quick google of your error led me to this, although I am not 100% sure it 
will solve your issue… however, it is worth trying at a minimum.

https://stackoverflow.com/questions/17594211/you-are-not-allowed-to-edit-this-selection-because-it-is-protected-but-only-s

They suggest changing the View and explain that Microsoft blocks certain thing 
in Reading Layout.

This linked website also has some comments about changing security settings of 
the document in the Trust Center which may also be of some help, but I did not 
validate or test their suggestions.

Good luck, as I did not have this problem (likely because I started from a 
blank document).

Steven
From: Ryan Dikdan 
Sent: Thursday, March 16, 2023 10:12 PM
To: Steven Manross ; python-win32@python.org
Subject: Re: How to add citations to a word document

Thank you!! I've made a lot of progress. I've been able to reformat citations, 
but I've hit another roadbump that chat gpt can't help me with anymore. I 
successfully have a script that can take a citation file and load it into word 
and automatically place a citation, but if I want to put a citation on top of 
an existing citation Field, it says that the field is protected. I can't find a 
way to unprotect it, either through the selection or the document itself. 
Here's my code:

`word = win32.GetActiveObject("Word.Application")

doc = word.ActiveDocument

doc.Bibliography.Sources.Add(xml_string)

cursor_pos = word.Selection.Range.Start

fields = doc.Fields
current_field = None
for field in fields:
if cursor_pos >= field.Result.Start and cursor_pos <= field.Result.End:
current_field = field
break

if current_field is not None:
if current_field.Type == win32.constants.wdFieldCitation:
current_code = current_field.Code.Text
# \\m is just used to show that there are multiple sources in 
this one citation.
current_field.Code.Text = current_code + f'\\m {tag}'
else:
# \\l 1033 just says means that it's in english
current_field = doc.Range(cursor_pos, 
cursor_pos).Fields.Add(doc.Range(cursor_pos, cursor_pos), 
win32.constants.wdFieldCitation, Text=f" {tag} \\l 1033", 
PreserveFormatting=True)

current_field.Update()`

But this gives the error pywintypes.com_error:
(-2147352567, 'Exception occurred.', (0, 'Microsoft Word', 'You are not allowed 
to edit this selection because it is protected.', 'wdmain11.chm', 25604, 
-2146822164), None)​

when the cursor is inside of another field. Any other way to edit or unprotect 
the field would be appreciated. I was thinking of deleting and remaking the 
field, but this duplicates the references I think.


 Yours truly,
  Ryan Dikdan
________
From: Steven Manross mailto:ste...@manross.net>>
Sent: Wednesday, March 1, 2023 6:43 PM
To: Ryan Dikdan mailto:rjd...@njms.rutgers.edu>>; 
python-win32@python.org<mailto:python-win32@python.org> 
mailto:python-win32@python.org>>
Subject: RE: How to add citations to a word document

I'd probably start by creating a test Word document and adding a source 
manually in it from the Word GUI.

Then, I would likely want to do something like this in python.

# Sample python to list the bibliography entries
import win32com.client


wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")

wordapp.Visible = True

doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx")

for source in doc.Bibliography.Sources:
print("source: " + source.XML)
# Now save the XML as a variable:
myxml = source.XML

wordapp.Quit()

That should give you the properly formatted source XML that Word is looking 
for  And you can then modify a known working version of the XML so you can 
add all your bibliographical information in Word.

My test (using the above process) showed up like this:

https://nam02.safelinks.protection.outlook.com/?url=http%3A%2F%2Fschemas.openxmlformats.org%2FofficeDocument%2F2006%2Fbibliography=05%7C01%7Crjd254%40njms.rutgers.edu%7C1eb7c0945071410f7a2c08db1aaeb821%7Cb92d2b234d35447093ff69aca6632ffe%7C1%7C0%7C638133110076478769%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C=AsqVPr1onGfezeYnBY4NpCgC3PZBfeVTqHO8Ird%2FdTs%3D=0;>Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenhttps://nam02.safelinks.protection.outlook.com/?url=http%3A%2F%2Fschemas.openxmlformats.org%2FofficeDocument%2F2006%2Fbibliography=05%7C01%7Crjd254%40njms.rutgers.edu%7C1eb7c0945071410f7a2c08db1aaeb821%7Cb92d2b234d35447093ff69aca6632ffe%7C1%7C0%7C638133110076478769%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C=AsqVPr1onGfezeYnBY4NpCgC3PZBfeVTqHO8Ird%2FdTs%3D=0%22%3e%3cb:Tag%3eSte20%3c/b:Tag%3e%3cb:SourceType%3eBook%3c/b:SourceType%3e%3cb:Guid%3e%7b92931D8B-470B-4359-A4B8-3C53859A1B3F%7d%3c/b:Guid%3e%3cb:Author%3e%3cb:Author%3e%3cb:NameList%3

Re: [python-win32] How to add citations to a word document

2023-03-01 Thread Steven Manross
I'd probably start by creating a test Word document and adding a source 
manually in it from the Word GUI.

Then, I would likely want to do something like this in python.

# Sample python to list the bibliography entries
import win32com.client


wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")

wordapp.Visible = True

doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx")

for source in doc.Bibliography.Sources:
print("source: " + source.XML)
# Now save the XML as a variable:
myxml = source.XML

wordapp.Quit()

That should give you the properly formatted source XML that Word is looking 
for  And you can then modify a known working version of the XML so you can 
add all your bibliographical information in Word.

My test (using the above process) showed up like this:

http://schemas.openxmlformats.org/officeDocument/2006/bibliography;>Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenHow
 To Add A Bibliography Entry2023Nowhere, AZ< 
/b:City>Some Really Good 
Publisher1


# NOW use the Word GUI to Delete the source from the Bibliography info then 
save the document using the GUI

And then you can use the code above to verify there are no more sources:

And last but not least, re-add your source info programmatically:

import win32com.client


wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")

wordapp.Visible = True

doc = wordapp.Documents.Open(r"C:\\temp\\testing.docx")

myxml = 'http://schemas.openxmlformats.org/officeDocument/2006/bibliography;>Ste20Book{92931D8B-470B-4359-A4B8-3C53859A1B3F}ManrossStevenHow
 To Add A Bibliography Entry2023Nowhere, AZ< 
/b:City>Some Really Good 
Publisher1'

doc.Bibliography.Sources.Add(myxml)

doc.Save()
wordapp.Quit()


I'm pretty sure that your Bibliography XML is likely not formatted the way Word 
wants it..  Microsoft likes their own formats on everything.

If It matters, I tested this using Word 2019 but it should be backwards 
compatible all the way back to 2007.

HTH and Enjoy

P.S. This is not something that is limited to Python..  It can be done in just 
about any language that can access COM objects...  VBScript, Perl, Python, etc 
and there are tons of references on using VB and or VBScript macros that I 
found (but not much on exactly what the source XML looked like)

From: python-win32  On 
Behalf Of Ryan Dikdan
Sent: Tuesday, February 28, 2023 11:35 PM
To: python-win32@python.org
Subject: [python-win32] How to add citations to a word document

Hello, I'm not sure how this mailing list works for support, but I'm trying to 
make a python script that formats downloaded citations and inserts them into 
word (avoiding all the hassle of external citation managers). I found pywin32 
as the only way, but the documentation on doc.Bibliography.Sources.Add is 
scarce, so I was wondering if you all could help me. I have properly formatted 
xml of sources (since I could upload it to the source manager successfully, 
even though I think it's encoded in utf8 bom or sig or something). But whenever 
I put either the string of that content or the filename into the above Add() 
command in python it says the XML isn't formatted properly. I'd appreciate any 
help. Thanks!
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] taskscheduler: how to tick setting "Run task as soon as possible after scheduled start is missed"

2023-01-08 Thread Steven Manross
I haven’t seen a response for this yet, but…  I have done work with the 
TaskScheduler in powershell, and in powershell you can do something like this:

PS C:\Users\Administrator.DOMAIN> (Get-ScheduledTask -TaskName mytask).Settings

AllowDemandStart: True
AllowHardTerminate  : True
Compatibility   : Win8
DeleteExpiredTaskAfter  :
DisallowStartIfOnBatteries  : True
Enabled : True
ExecutionTimeLimit  : PT72H
Hidden  : False
IdleSettings: MSFT_TaskIdleSettings
MultipleInstances   : IgnoreNew
NetworkSettings : MSFT_TaskNetworkSettings
Priority: 7
RestartCount: 0
RestartInterval :
RunOnlyIfIdle   : False
RunOnlyIfNetworkAvailable   : False
StartWhenAvailable  : False
StopIfGoingOnBatteries  : True
WakeToRun   : False
DisallowStartOnRemoteAppSession : False
UseUnifiedSchedulingEngine  : True
MaintenanceSettings :
volatile: False
PSComputerName  :

“StartWhenAvailable” is what you are looking for.  You would set it to True

I don’t know how to get at the TaskScheduler from python without directing you 
to importing C DLLs and using the ctypes module, but I hope this helps.

As well, here is some documentation on TaskScheduler for Powershell

https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtasksettingsset?view=windowsserver2022-ps

Sorry, it’s not docs for python but I hope it helps you get closer to what you 
are looking for.

HTH

Steven
From: python-win32  On 
Behalf Of Joel Moberg
Sent: Thursday, January 5, 2023 6:18 AM
To: python-win32@python.org
Subject: [python-win32] taskscheduler: how to tick setting "Run task as soon as 
possible after scheduled start is missed"

Maybe I can adjust the flag in the Trigger object but I have no idea what flags 
are available.
[cid:image001.png@01D92230.B0567150]
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] pywin32 in python 64bit-3.7 environment

2022-07-05 Thread Steven Manross
https://anaconda.org/anaconda/pywin32

... suggests:

conda install -c anaconda pywin32

BUT, that is version 302 according to the URL above.

As for the EXE, I don't think that PIP will install from an EXE.

I hope this helps, but I literally know nothing about anaconda.  I'm sure that 
someone else likely knows more.

Steven
From: python-win32  On 
Behalf Of De Silva, Thushara via python-win32
Sent: Tuesday, July 5, 2022 2:13 PM
To: python-win32@python.org
Subject: [python-win32] pywin32 in python 64bit-3.7 environment

Hi,
I am working in python 64-bit, 3.7 environment. I want to install pywin32 to 
conda-environment.
"pip install pywin32" installed pywin32 304 to my env. But I cannot "import 
pywin32" from my jupyter notebook (No Module named 'pywin32'). I assumed, I 
have to install 64 bit pywin 32.

So, I tried to install the module as
pip install 
https://github.com/mhammond/pywin32/releases/download/b304/pywin32-304.win-amd64-py3.7.exe

ERROR: File "setup.py" not found for legacy project 
https://github.com/mhammond/pywin32/releases/download/b304/pywin32-304.win-amd64-py3.7.exe.

Would you all help me?

Thanks,
Thushara
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Need a value from pywin32

2022-06-22 Thread Steven Manross
We have a winner!

Huge thanks from me even though I wasn’t the OP because I've wanted to know how 
to do this for a while and just started to get my feet wet in this arena!!!  I 
now have a VERY GOOD EXAMPLE of how to start looking at doing a complex task 
like this with all the nested references.  UGH!

In [16]: get_idle_time(2)  # session id = 2
Out[16]: 0.0156271

Please note that line wraps (and or a missing newline) in the previous email 
may cause copy/paste issues in Eryk's code around these lines:

winsta.WinStationQueryInformationW.restype = wintypes.BOOLEAN
# this needs to be a newline
winsta.WinStationQueryInformationW.argtypes = (
wintypes.HANDLE, # ServerHandle
wintypes.ULONG,  # SessionId
ctypes.c_long,   # WinStationInformationClass
wintypes.LPVOID, # pWinStationInformation
wintypes.ULONG,  # WinStationInformationLength
wintypes.PULONG, # pReturnLength
)

I HOPE THIS HELPS AND THANK YOU VERY MUCH!

Steven
-Original Message-
From: Eryk Sun  
Sent: Wednesday, June 22, 2022 1:28 PM
To: Steven Manross 
Cc: python-win32@python.org
Subject: Re: [python-win32] Need a value from pywin32

On 6/21/22, Steven Manross  wrote:
>
> class WinStationInformation(ctypes.Structure):
> __fields__ = [
> ('ConnectState', ctypes.c_long),
> ('WinStationName', ctypes.wintypes.WCHAR),
> ('LogonId', ctypes.c_ulong),
> ('ConnectTime', ctypes.wintypes.LARGE_INTEGER),
> ('DisconnectTime', ctypes.wintypes.LARGE_INTEGER),
> ('LastInputTime', ctypes.wintypes.LARGE_INTEGER),
> ('LogonTime', ctypes.wintypes.LARGE_INTEGER),
> ('Status', ctypes.c_int()),
> ('Domain', ctypes.wintypes.WCHAR * (17 + 1)),
> ('UserName', ctypes.wintypes.WCHAR * (20 + 1)),
> ('CurrentTime', ctypes.wintypes.LARGE_INTEGER),
> ]

The above definition is incorrect for `WinStationName` and `Status`.
Defining the PROTOCOLSTATUS type for `Status` is tedious. Note also that the 
ctypes attribute to set is `_fields_`, not `__fields__`, so the above struct is 
actually defined with no fields (i.e. zero size).

Here's an example that defines a get_idle_time() function, based on the 
difference between the current time and the last input time in the session.

import ctypes
from ctypes import wintypes

winsta = ctypes.WinDLL('winsta', use_last_error=True)

WINSTATIONNAME_LENGTH = 32
DOMAIN_LENGTH = 17
USERNAME_LENGTH = 20
MAX_THINWIRECACHE = 4

SERVERNAME_CURRENT = None
LOGONID_CURRENT = -1

# WINSTATIONINFOCLASS
WinStationInformation = 8

# WINSTATIONSTATECLASS
State_Active = 0
State_Connected = 1
State_ConnectQuery = 2
State_Shadow = 3
State_Disconnected = 4
State_Idle = 5
State_Listen = 6
State_Reset = 7
State_Down = 8
State_Init = 9

class TSHARE_COUNTERS(ctypes.Structure):
__slots__ = ()
_fields_ = (
('Reserved', wintypes.ULONG),
)

class PROTOCOLCOUNTERS(ctypes.Structure):
__slots__ = ()
class SPECIFIC(ctypes.Union):
__slots__ = ()
_fields_ = (
('TShareCounters', TSHARE_COUNTERS),
('Reserved', wintypes.ULONG * 100),
)
_fields_ = (
('WdBytes', wintypes.ULONG),
('WdFrames', wintypes.ULONG),
('WaitForOutBuf', wintypes.ULONG),
('Frames', wintypes.ULONG),
('Bytes', wintypes.ULONG),
('CompressedBytes', wintypes.ULONG),
('CompressFlushes', wintypes.ULONG),
('Errors', wintypes.ULONG),
('Timeouts', wintypes.ULONG),
('AsyncFramingError', wintypes.ULONG),
('AsyncOverrunError', wintypes.ULONG),
('AsyncOverflowError', wintypes.ULONG),
('AsyncParityError', wintypes.ULONG),
('TdErrors', wintypes.ULONG),
('ProtocolType', wintypes.USHORT),
('Length', wintypes.USHORT),
('Specific', SPECIFIC),
)


class THINWIRECACHE (ctypes.Structure):
__slots__ = ()
_fields_ = (
('CacheReads', wintypes.ULONG),
('CacheHits', wintypes.ULONG),
)


class RESERVED_CACHE(ctypes.Structure):
__slots__ = ()
_fields_ = (
('ThinWireCache[', THINWIRECACHE * MAX_THINWIRECACHE),
)


class CACHE_STATISTICS(ctypes.Structure):
__slots__ = ()
class SPECIFIC(ctypes.Union):
__slots__ = ()
_fields_ = (
('ReservedCacheStats', RESERVED_CACHE),
('TShareCacheStats', wintypes.ULONG),
('Reserved', wintypes.ULONG * 20),
)
_fields_ = (
('ProtocolType', wintypes.USHORT),
('Length', wintypes.USHORT),
('Specific', SPECIFIC),
)


class PROTOCOLSTATUS(ctypes.Structure):
__slots__ = ()
_fields_ = (
('Output', PROTOCOLCOUNTERS),
('Input', PROTOCOLCOUNTERS),
('Cache', CACHE_STATISTICS),
('AsyncSignal', wintypes.ULONG),
('AsyncSignalMask', wintypes.ULONG),
)


class WINSTATIONINFORMATION(ctypes.Structure):
__slots__ = ()
_field

Re: [python-win32] Need a value from pywin32

2022-06-22 Thread Steven Manross
Thanks a lot for the help!!!

This is no longer Excepting...  But the Result is 0 and there doesn't seem to 
be any data in the Buf structure or indication that there were results in 
RtnLen...  I get to debug this more..  YAY!!!

Steven
-Original Message-
From: python-win32  On 
Behalf Of Tim Roberts
Sent: Tuesday, June 21, 2022 10:04 PM
To: python-win32@python.org
Subject: Re: [python-win32] Need a value from pywin32

On 6/21/22 13:39, Steven Manross wrote:

> I was intrigued by this and I would like to get it to work, but I cannot...  
> I know I'm doing something wrong, but don't know what.  I will leave this for 
> the archives, and maybe it will help someone else some day.
> ...
> def get_wts_info(session_id):
>  '''
>  Get WTS Info
>  '''
>  # This only tries to work on the local server currently but I get 
> an access violation running the WinStationQueryInformationW line
>
>  Buf = ctypes.POINTER(WinStationInformation)()
>  BufLen = 260
>
>  hWinSta = ctypes.windll.LoadLibrary("WINSTA.DLL")
>  if hWinSta:
>  winsta_handle = hWinSta._handle
>  print(f'winsta_handle = {winsta_handle}')
>  QueryInfoHandle = 
> ctypes.windll.kernel32.GetProcAddress(ctypes.c_ulonglong(winsta_handle
> ), b"WinStationQueryInformationW")
>
>  # This handle is 0...  possibly because of the numeric 
> conversion from the winsta_handle to a ctypes.c_ulonglong  ???  unsure

No, 0 is the error return that means the name was not found.

You shouldn't need to use LoadLibrary and GetProcAddress.  ctypes does that for 
you automatically.

     winsta = ctypes.WinDLL('winsta.dll')

     winsta.WinStationQueryInformationW( 0, session_id, 8, ctypes.byref(Buf), 
BufLen, ctypes.byref(RtnLen))

If you have Visual Studio, you can try doing "link /dump /exports 
\windows\system32\winsta.dll" to make sure it has that entry point.

--
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Need a value from pywin32

2022-06-21 Thread Steven Manross
I was intrigued by this and I would like to get it to work, but I cannot...  I 
know I'm doing something wrong, but don't know what.  I will leave this for the 
archives, and maybe it will help someone else some day.

My guess is that the issue is the conversion of the winsta_handle to a 
ctypes.c_ulonglong() is generating an invalid handle ID or the GetProcAddress 
isn't finding the correct info using that handle.

I'm very new to C programming

'''
Get Terminal Services Idle Time and other values from WINSTA.DLL for local 
server

> THIS DOES NOT WORK!  <
> ONLY SENT AS STARTER CODE FOR SOMEONE TO FIGURE OUT WHAT I AM MISSING 
<

Microsoft Info:  
https://docs.microsoft.com/en-us/previous-versions/aa383827(v=vs.85)
Google Thread: 
https://groups.google.com/g/microsoft.public.win32.programmer.kernel/c/xt2G599tJuQ?hl=en=1#91fc4e79a5d6c495
'''
import ctypes

class WinStationInformation(ctypes.Structure):
__fields__ = [
('ConnectState', ctypes.c_long),
('WinStationName', ctypes.wintypes.WCHAR),
('LogonId', ctypes.c_ulong),
('ConnectTime', ctypes.wintypes.LARGE_INTEGER),
('DisconnectTime', ctypes.wintypes.LARGE_INTEGER),
('LastInputTime', ctypes.wintypes.LARGE_INTEGER),
('LogonTime', ctypes.wintypes.LARGE_INTEGER),
('Status', ctypes.c_int()),
('Domain', ctypes.wintypes.WCHAR * (17 + 1)),
('UserName', ctypes.wintypes.WCHAR * (20 + 1)),
('CurrentTime', ctypes.wintypes.LARGE_INTEGER),
]

def get_wts_info(session_id):
'''
Get WTS Info
'''
# This only tries to work on the local server currently but I get an access 
violation running the WinStationQueryInformationW line

Buf = ctypes.POINTER(WinStationInformation)()
BufLen = 260

hWinSta = ctypes.windll.LoadLibrary("WINSTA.DLL")
if hWinSta:
winsta_handle = hWinSta._handle
print(f'winsta_handle = {winsta_handle}')
QueryInfoHandle = 
ctypes.windll.kernel32.GetProcAddress(ctypes.c_ulonglong(winsta_handle), 
b"WinStationQueryInformationW")

# This handle is 0...  possibly because of the numeric conversion from 
the winsta_handle to a ctypes.c_ulonglong  ???  unsure
# I had to convert it because the handle was generating an error as a 
regular value:
#  ArgumentError: argument 1: : int too long to 
convert
#
print(f'QueryInfoHandle = {QueryInfoHandle}')  
WinStationQueryInformationW = hWinSta._FuncPtr(QueryInfoHandle)

RtnLen = ctypes.c_ulong()
try:
Result = WinStationQueryInformationW(0, session_id, 8, 
ctypes.byref(Buf), BufLen, ctypes.byref(RtnLen))
except Exception as e:
print(f'Excepted running WinStationQueryInformationW: {e}')
return False

print(f'Result = {Result}')
return True

get_wts_info(11) 
# where 11 is a valid session id on the local RDP server as defined by:
# Server Manager -> Remote Desktop Services -> Collections -> your 
Collection Name -> Connections
#Right Click on the columns in Connections Tab and add "ID" to the list 
of columns

My output:
   
winsta_handle = 140703764119552
QueryInfoHandle = 0
Excepted running WinStationQueryInformationW: exception: access violation 
writing 0x

HTH

Steven
-Original Message-
From: python-win32  On 
Behalf Of Tim Roberts
Sent: Monday, June 20, 2022 10:06 AM
To: python-win32@python.org
Subject: Re: [python-win32] Need a value from pywin32

Craig R. Matthews wrote:
>
> I have a need to determine the "IDLE TIME" as provided by the Windows 
> Query program.
>
> Sample output:
> C:\>query user /server:CTX202201
>  USERNAME  SESSIONNAME    ID  STATE   IDLE TIME LOGON 
> TIME
>  administrator rdp-tcp#67  2  Active   1:38
> 6/15/2022 10:48 AM
>
> I can't find the above "IDLE TIME" anywhere in pywin32 "Python for
> Win32 Extensions".
>
> I need this time value, and would rather keep all the code in python 
> without having to resort to something like subprocess to encapsulate 
> the Windows Query program.

This is part of Windows Terminal Services.  The API to fetch the idle time is 
undocumented and unsupported, but you can find the information here:

https://groups.google.com/g/microsoft.public.win32.programmer.kernel/c/xt2G599tJuQ?hl=en#91fc4e79a5d6c495

Because it is undocumented, it might be better to parse the output of "query 
user".

--
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Load custom font

2022-06-09 Thread Steven Manross
Sorry…

But, I need to Give credit where credit is due.

https://superuser.com/questions/1432800/get-actual-font-name-of-ttf-file-from-command-line

From: python-win32  On 
Behalf Of Steven Manross
Sent: Thursday, June 9, 2022 12:24 PM
To: Jérémie Bergeron ; python-win32@python.org
Subject: Re: [python-win32] Load custom font

Here’s a more windows centric approach and it foreaches through all the Windows 
fonts:
  ** It’s interesting that it says that it was last modified today…  odd, but 
whatever

from win32com.client.dynamic import Dispatch

ids = 
[0,1,2,3,4,5,6,9,10,19,21,25,33,34,58,62,165,166,167,170,191,192,193,195,197,203,255]

shell_app = Dispatch('Shell.Application')
shell_app.Namespace('c:\\windows\\fonts')
folder = shell_app.Namespace('c:\\windows\\fonts')
myfile = ""

for font in folder.Items():
print(font.Name)
#if font.Name == "Verdana":
#break

for num in ids:
val = None
val = folder.GetDetailsOf(font, num)
item = folder.GetDetailsOf(None, num)
if val:
print("\t", num, f'{item} = {val}')

**
partial output:
**
Verdana
 0 Name = Verdana
 1 Font style = Regular; Bold; Bold Italic; Italic
 2 Show/hide = Show
 3 Designed for = Latin; Greek; Cyrillic
 4 Category = Text
 5 Designer/foundry = Carter + Cone
 6 Font embeddability = Editable
 10 Date modified = ‎6/‎9/‎2022 ‏‎11:16 AM

From: python-win32 
mailto:python-win32-bounces+steven=manross@python.org>>
 On Behalf Of Jérémie Bergeron
Sent: Wednesday, June 8, 2022 6:28 AM
To: python-win32@python.org<mailto:python-win32@python.org>
Subject: [python-win32] Load custom font

Hi,

Is it possible to get the family name of a font and/or any other information 
from the naming table from a font file?

Something like that:
font = win32ui.loadFont(pathToTheFont)
familyName = font.getNameId(1)

Have a nice day
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Load custom font

2022-06-09 Thread Steven Manross
Here’s a more windows centric approach and it foreaches through all the Windows 
fonts:
  ** It’s interesting that it says that it was last modified today…  odd, but 
whatever

from win32com.client.dynamic import Dispatch

ids = 
[0,1,2,3,4,5,6,9,10,19,21,25,33,34,58,62,165,166,167,170,191,192,193,195,197,203,255]

shell_app = Dispatch('Shell.Application')
shell_app.Namespace('c:\\windows\\fonts')
folder = shell_app.Namespace('c:\\windows\\fonts')
myfile = ""

for font in folder.Items():
print(font.Name)
#if font.Name == "Verdana":
#break

for num in ids:
val = None
val = folder.GetDetailsOf(font, num)
item = folder.GetDetailsOf(None, num)
if val:
print("\t", num, f'{item} = {val}')

**
partial output:
**
Verdana
 0 Name = Verdana
 1 Font style = Regular; Bold; Bold Italic; Italic
 2 Show/hide = Show
 3 Designed for = Latin; Greek; Cyrillic
 4 Category = Text
 5 Designer/foundry = Carter + Cone
 6 Font embeddability = Editable
 10 Date modified = ‎6/‎9/‎2022 ‏‎11:16 AM

From: python-win32  On 
Behalf Of Jérémie Bergeron
Sent: Wednesday, June 8, 2022 6:28 AM
To: python-win32@python.org
Subject: [python-win32] Load custom font

Hi,

Is it possible to get the family name of a font and/or any other information 
from the naming table from a font file?

Something like that:
font = win32ui.loadFont(pathToTheFont)
familyName = font.getNameId(1)

Have a nice day
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Load custom font

2022-06-09 Thread Steven Manross
While this isn't win32ui, I hope it helps.

pip install Pillow

from PIL import ImageFont
font = ImageFont.truetype("c:\\windows\\Fonts\\verdana.ttf", 28, 
encoding="unic")
font.font.family
font.font.height
font.font.style

google search revealed this:

https://stackoverflow.com/questions/24085996/how-i-can-load-a-font-file-with-pil-imagefont-truetype-without-specifying-the-ab

HTH

Steven
From: python-win32  On 
Behalf Of Jérémie Bergeron
Sent: Wednesday, June 8, 2022 6:28 AM
To: python-win32@python.org
Subject: [python-win32] Load custom font

Hi,

Is it possible to get the family name of a font and/or any other information 
from the naming table from a font file?

Something like that:
font = win32ui.loadFont(pathToTheFont)
familyName = font.getNameId(1)

Have a nice day
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Inquiry about Sending HTML format in Appointment in Outlook Application

2022-05-27 Thread Steven Manross
As I recall, Calendar Items are a special kind of MailItem, and there is Body 
and BodyHTML on a mailItem which represent the “Text Body” and the “HTMLBody”.

https://docs.microsoft.com/en-us/office/vba/api/outlook.mailitem.bodyformat

As well, there is a MailItem.BodyFormat which is supposed to be set to 
olFormatHTML per the document above.

olBodyFormat enumeration docs are here:
https://docs.microsoft.com/en-us/office/vba/api/outlook.olbodyformat

They have some VBScript in the top URL that should be somewhat easy to convert 
to Python.

HTH

Steven
From: python-win32  On 
Behalf Of Ishaan Sathe
Sent: Friday, May 27, 2022 8:57 AM
To: python-win32@python.org
Subject: [python-win32] Inquiry about Sending HTML format in Appointment in 
Outlook Application

Hii All ,
I am trying to send the Body in the Calendar invite in Outlook as HTML.
Can somebody help me how to do this ?

Thanks

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Import Certificate with Private Key to Current Computer Certificate store

2022-05-27 Thread Steven Manross
pythonnet for the win!!! (.NET for Python)

P.S. I couldn't install from pip (visual studio dependency issues) but the 
wheel file below worked like a charm (for python 3.9).  Problem solved.  

https://download.lfd.uci.edu/pythonlibs/a4hvik9m/pythonnet-2.5.2-cp39-cp39-win_amd64.whl

# pip install pythonnet-2.5.2-cp39-cp39-win_amd64.whl

'''
Install a PFX (Certificate with Key) file to the Windows Local Computer (not 
current user) Personal store
 (typically where IIS looks for SSL Certificates)
'''
import clr
from System.Security.Cryptography.X509Certificates import X509Certificate2
from System.Security.Cryptography.X509Certificates import X509Store
from System.Security.Cryptography.X509Certificates import X509KeyStorageFlags
from System.Security.Cryptography.X509Certificates import OpenFlags
from System.Security.Cryptography.X509Certificates import StoreName, 
StoreLocation


pfx = X509Certificate2()
store = X509Store(StoreName.My, StoreLocation.LocalMachine)

passw = None
pfx.Import('c:/mypfx.pfx', passw, X509KeyStorageFlags.Exportable | 
X509KeyStorageFlags.PersistKeySet)

store.Open(OpenFlags.MaxAllowed)
store.Add(pfx)
store.Close()

Kudos to the below powershell script for the primer that I adapted to 
Python.NET.

https://gist.github.com/smaglio81/19146391f7f94e2449e16d3318be1ef7

Steven
-Original Message-
From: Steven Manross  
Sent: Thursday, May 26, 2022 7:32 PM
To: Steven Manross ; mhamm...@skippinet.com.au; 
python-win32@python.org
Subject: RE: [python-win32] Import Certificate with Private Key to Current 
Computer Certificate store

As much as I don’t like shelling out to a command prompt...   

CERTUTIL -f -p "" -importpfx "c:\mycertwithpfx.pfx"

There's definitely a different API for Certs with Private keys as best I can 
tell...  I just cant find what it is 100%.

THANKS FOR YOUR HELP!

At least I can get it done (for now).

Steven
-Original Message-
From: python-win32  On 
Behalf Of Steven Manross
Sent: Thursday, May 26, 2022 5:49 PM
To: mhamm...@skippinet.com.au; python-win32@python.org
Subject: Re: [python-win32] Import Certificate with Private Key to Current 
Computer Certificate store

I'll give it a shot...  Thanks!

Steven

-Original Message-
From: Mark Hammond 
Sent: Thursday, May 26, 2022 5:45 PM
To: Steven Manross ; python-win32@python.org
Subject: Re: [python-win32] Import Certificate with Private Key to Current 
Computer Certificate store

Hi!

I know almost nothing about certificate stores, but as luck would have it, 
someone did report some issues recently, so it turns out there is a PR that (a) 
tries to fix a couple of issues and (b) adds a test that adds certificates to 
the store - see https://github.com/mhammond/pywin32/pull/1863, particularly 
test_win32crypt.py, which can hopefully be found at
https://github.com/mhammond/pywin32/pull/1863/files#diff-9f6fa3983d625ad71f59c9b4662dc07ea20602ffb5c3b1aa58e5e59fa759dff7

HTH,

Mark

On 27/05/2022 10:40 am, Steven Manross wrote:
> Howdy,
> 
> I am finishing up some work on requesting certificates from an internal 
> Microsoft CA, and then importing the certs to the local windows certificate 
> store, butd was having difficulty determining what function to use to import 
> a Certificate with Private Key (P12/PFX) to a the computer's Certificate 
> store.  I've got everything else handled up to this point (I think), but now 
> I am stuck.
> 
> I see two possible functions for likely adding the certificate to the store:
>   
> http://timgolden.me.uk/pywin32-docs/win32crypt__CertAddSerializedElementToStore_meth.html
>   * likely the way to go, but I don't see in the documentation 
> how to take my Cert with Key and convert it to the necessary structure
>   
> http://timgolden.me.uk/pywin32-docs/win32crypt__PFXImportCertStore_meth.html
>   * this one I'm not so sure about (not likely what I want to do)
> 
> ...but  also see this:
>   
> https://stackoverflow.com/questions/61888404/how-do-i-install-a-certificate-to-trusted-root-certificates-using-python
>   * however I cannot read the PFX correctly (presumably due to 
> the encrypted nature of the certificate with key).
>   * I DO have the base64 PEM crt and key files if that helps me 
> in this process
>   * the CertStore code from this post looks like what I need to 
> get to 
> the CertStore, however
> 
> The certificates I'm trying to work with are typically for webserver renewals.
> 
> If anyone has knowledge and is willing to share, I'd appreciate it!
> 
> Please and Thank you,
> Steven
> ___
> python-win32 mailing list
> python-win32@python.org
> https://mail.python.org/mailman/listinfo/python-win32

___
python-win32 mailing list
python-win32@python.o

Re: [python-win32] Import Certificate with Private Key to Current Computer Certificate store

2022-05-26 Thread Steven Manross
As much as I don’t like shelling out to a command prompt...   

CERTUTIL -f -p "" -importpfx "c:\mycertwithpfx.pfx"

There's definitely a different API for Certs with Private keys as best I can 
tell...  I just cant find what it is 100%.

THANKS FOR YOUR HELP!

At least I can get it done (for now).

Steven 
-Original Message-
From: python-win32  On 
Behalf Of Steven Manross
Sent: Thursday, May 26, 2022 5:49 PM
To: mhamm...@skippinet.com.au; python-win32@python.org
Subject: Re: [python-win32] Import Certificate with Private Key to Current 
Computer Certificate store

I'll give it a shot...  Thanks!

Steven

-Original Message-
From: Mark Hammond 
Sent: Thursday, May 26, 2022 5:45 PM
To: Steven Manross ; python-win32@python.org
Subject: Re: [python-win32] Import Certificate with Private Key to Current 
Computer Certificate store

Hi!

I know almost nothing about certificate stores, but as luck would have it, 
someone did report some issues recently, so it turns out there is a PR that (a) 
tries to fix a couple of issues and (b) adds a test that adds certificates to 
the store - see https://github.com/mhammond/pywin32/pull/1863, particularly 
test_win32crypt.py, which can hopefully be found at
https://github.com/mhammond/pywin32/pull/1863/files#diff-9f6fa3983d625ad71f59c9b4662dc07ea20602ffb5c3b1aa58e5e59fa759dff7

HTH,

Mark

On 27/05/2022 10:40 am, Steven Manross wrote:
> Howdy,
> 
> I am finishing up some work on requesting certificates from an internal 
> Microsoft CA, and then importing the certs to the local windows certificate 
> store, butd was having difficulty determining what function to use to import 
> a Certificate with Private Key (P12/PFX) to a the computer's Certificate 
> store.  I've got everything else handled up to this point (I think), but now 
> I am stuck.
> 
> I see two possible functions for likely adding the certificate to the store:
>   
> http://timgolden.me.uk/pywin32-docs/win32crypt__CertAddSerializedElementToStore_meth.html
>   * likely the way to go, but I don't see in the documentation 
> how to take my Cert with Key and convert it to the necessary structure
>   
> http://timgolden.me.uk/pywin32-docs/win32crypt__PFXImportCertStore_meth.html
>   * this one I'm not so sure about (not likely what I want to do)
> 
> ...but  also see this:
>   
> https://stackoverflow.com/questions/61888404/how-do-i-install-a-certificate-to-trusted-root-certificates-using-python
>   * however I cannot read the PFX correctly (presumably due to 
> the encrypted nature of the certificate with key).
>   * I DO have the base64 PEM crt and key files if that helps me 
> in this process
>   * the CertStore code from this post looks like what I need to 
> get to 
> the CertStore, however
> 
> The certificates I'm trying to work with are typically for webserver renewals.
> 
> If anyone has knowledge and is willing to share, I'd appreciate it!
> 
> Please and Thank you,
> Steven
> ___
> python-win32 mailing list
> python-win32@python.org
> https://mail.python.org/mailman/listinfo/python-win32

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Import Certificate with Private Key to Current Computer Certificate store

2022-05-26 Thread Steven Manross
I'll give it a shot...  Thanks!

Steven

-Original Message-
From: Mark Hammond  
Sent: Thursday, May 26, 2022 5:45 PM
To: Steven Manross ; python-win32@python.org
Subject: Re: [python-win32] Import Certificate with Private Key to Current 
Computer Certificate store

Hi!

I know almost nothing about certificate stores, but as luck would have it, 
someone did report some issues recently, so it turns out there is a PR that (a) 
tries to fix a couple of issues and (b) adds a test that adds certificates to 
the store - see https://github.com/mhammond/pywin32/pull/1863, particularly 
test_win32crypt.py, which can hopefully be found at
https://github.com/mhammond/pywin32/pull/1863/files#diff-9f6fa3983d625ad71f59c9b4662dc07ea20602ffb5c3b1aa58e5e59fa759dff7

HTH,

Mark

On 27/05/2022 10:40 am, Steven Manross wrote:
> Howdy,
> 
> I am finishing up some work on requesting certificates from an internal 
> Microsoft CA, and then importing the certs to the local windows certificate 
> store, butd was having difficulty determining what function to use to import 
> a Certificate with Private Key (P12/PFX) to a the computer's Certificate 
> store.  I've got everything else handled up to this point (I think), but now 
> I am stuck.
> 
> I see two possible functions for likely adding the certificate to the store:
>   
> http://timgolden.me.uk/pywin32-docs/win32crypt__CertAddSerializedElementToStore_meth.html
>   * likely the way to go, but I don't see in the documentation 
> how to take my Cert with Key and convert it to the necessary structure
>   
> http://timgolden.me.uk/pywin32-docs/win32crypt__PFXImportCertStore_meth.html
>   * this one I'm not so sure about (not likely what I want to do)
> 
> ...but  also see this:
>   
> https://stackoverflow.com/questions/61888404/how-do-i-install-a-certificate-to-trusted-root-certificates-using-python
>   * however I cannot read the PFX correctly (presumably due to 
> the encrypted nature of the certificate with key).
>   * I DO have the base64 PEM crt and key files if that helps me 
> in this process
>   * the CertStore code from this post looks like what I need to 
> get to 
> the CertStore, however
> 
> The certificates I'm trying to work with are typically for webserver renewals.
> 
> If anyone has knowledge and is willing to share, I'd appreciate it!
> 
> Please and Thank you,
> Steven
> ___
> python-win32 mailing list
> python-win32@python.org
> https://mail.python.org/mailman/listinfo/python-win32

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


[python-win32] Import Certificate with Private Key to Current Computer Certificate store

2022-05-26 Thread Steven Manross
Howdy,

I am finishing up some work on requesting certificates from an internal 
Microsoft CA, and then importing the certs to the local windows certificate 
store, butd was having difficulty determining what function to use to import a 
Certificate with Private Key (P12/PFX) to a the computer's Certificate store.  
I've got everything else handled up to this point (I think), but now I am stuck.

I see two possible functions for likely adding the certificate to the store:

http://timgolden.me.uk/pywin32-docs/win32crypt__CertAddSerializedElementToStore_meth.html
* likely the way to go, but I don't see in the documentation 
how to take my Cert with Key and convert it to the necessary structure

http://timgolden.me.uk/pywin32-docs/win32crypt__PFXImportCertStore_meth.html
* this one I'm not so sure about (not likely what I want to do)

...but  also see this:

https://stackoverflow.com/questions/61888404/how-do-i-install-a-certificate-to-trusted-root-certificates-using-python
* however I cannot read the PFX correctly (presumably due to 
the encrypted nature of the certificate with key).
* I DO have the base64 PEM crt and key files if that helps me 
in this process
* the CertStore code from this post looks like what I need to 
get to the CertStore, however

The certificates I'm trying to work with are typically for webserver renewals.

If anyone has knowledge and is willing to share, I'd appreciate it!

Please and Thank you,
Steven
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] IIS ASP webpage issues with minimal pyscript

2022-05-21 Thread Steven Manross
I'm not sure what changed this time except that I renamed my C:\Python310 dir 
to C:\Python310--- after uninstalling and rebooting so it would install in a 
fresh directory, but now my ASP scripts are working.  YAY!!

Have a great day.

Chalk another one up to leaving the problem for a few hours, and you finally 
figure out a way around it.  

Steven
-Original Message-
From: Steven Manross 
Sent: Saturday, May 21, 2022 6:28 PM
To: python-win32@python.org
Subject: IIS ASP webpage issues with minimal pyscript

Howdy,

I have pywin32 ASP Scripts using Python 3.10.4 x64 (from Python.org) running on 
2 servers.  Both are Win Server 2016 with the most recent patches.

I am using pywin32==304

One server runs pyscript in ASP fine, the other doesn’t (VBScript works fine 
both servers).

This is the page I am trying to render in Classic ASP:

<%@ LANGUAGE="Python"%>
<%
Response.Write('This is a test')
%>

Note: if I render that Classic ASP code on another server, it renders correctly.

If I make my ASP page just this

<%@ LANGUAGE="Python"%>

No error appears, but obviously, I want to write something to the webpage, so 
sadly I have to debug this further.

This is the browser error I get from Chrome:

This site can’t be reached
The webpage at https://whatever.manross.net/mypage.asp might be temporarily 
down or it may have moved permanently to a new web address.
ERR_UNEXPECTED

In trying to debug this further, I found “DebugDiagx64” (a Microsoft tool) in 
order to trace the specific application pool I am having problems with (and 
enable diagnostic data when the apppool/process dies).

Here’s one of the trace analysis files it came up with (attached) and there 
were a total of 4 traces:
 * w3wp__debug-analysis.mht.txt (.txt was added in case MHT files are active 
content and stripped by anyone's servers).
 * Note: this analysis file renders in IE fine If you alter Internet 
Options -> Advanced -> Security -> Allow Active Content to run in files on My 
Computer (requires restart) to enabled
 * Iistrace-as-text.txt is just a text file where I pulled out some relevant 
data from the debugdiag analysis output presuming that not everyone has a 
windows system or wants to run that active content in a browser.

What I’ve tried in debugging this:
* run: python pyscript.py (and tried adding a --debug -- no errors on either 
running)
* run: python pywin32_postinstall.py --install (no errors)
* verified Application Pool does not have "Enable 32-bit Applications = True" 
(found out about that on the other server)
* created a new application pool and assigned it to the site, and made sure 
that it behaved the same..  it does (both don’t work).
* repaired the installation of Python 3.10.4 from "Add/Remove Programs"
* removed python and reinstalled python after a clean reboot
* iisreset.exe (stop/start IIS completely)
* reboot server a few times
* searching for answers on google for a few hours related to "App Pool crash" 
"Python" "Classic ASP" and more.
* reading the documentation: 
https://github.com/mhammond/pywin32/blob/main/README.md  again just in case 
* searched for pywintypes*.* and didn’t find any different versions that I 
thought would be a problem (note: some Intel SSD software has one in its 
personal application directory for python 2.7) Python itself is behaving just 
fine, and can instantiate COM objects as I have been testing/building 
"CertificateAuthority" python modules on this server in prep for creating a web 
page.  It's just when I start to make ASP pages that it goes crazy.

If anyone has suggestions, I can do just about anything to this PC at any time 
(other than del /s /q c:\*.*)  

Thanks for your time.

Steven
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Reading email body from Outlook: Operation aborted

2022-05-15 Thread Steven Manross
The one thing that I see in this code is:
   * there is a possible problem with how you are calling the 
Outlook.Application object, namely you are doing a "GetActiveObject" and this 
could fail if Outlook is not already open.

If you are sure that Outlook will always be open when you run your python code 
(or this was an easy way to show an example), then it shouldn't be a problem, 
but I just wanted to make sure that wasn't throwing a wrench into the mix that 
you weren't thinking about.

I'm using pywin32 v304 on Python 3.10 (x64) on Windows 10 x64 (21H2) with 
Outlook 2019 (not the Ofifce 365 version), and your code works fine for me so 
it's not a W10 thing or a v304 on W10 issue).
 
I went as far as this code (slightly different at the end but basically the 
same):

import win32com.client

outlook = 
win32com.client.GetActiveObject('Outlook.Application').GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6).Items
messages = list(inbox)
for message in messages:
print(message.Subject)

...and all was well.

#snipped output start
Backup Log: XX
WSUS: Update Status Summary From XX
WSUS: Update Status Summary From XXX
#snipped output end

Here's another possible problem: 
* the attached security warning popped up a few times while I was testing 
your code, and this could also be giving your python code issues (if the 
approve button isn’t pressed in X seconds or the deny button is pressed). 

 Back in the day of Outlook 2003, there were ways to publish something to your 
Public Folders in a specific folder path to tell Outlook that it should allow 
programmatic access (no matter what) for user X or Group Y, but just remember, 
most of the Outlook Automation that people typically have seen is created by 
hackers, so Microsoft had to lock it down a lot, and as such,  this type of 
warning shouldn't really be disabled except for maybe 1 - 5 minutes at a time 
by someone running the script who understands exactly what it's doing (and even 
then you are opening yourself to a security nightmare if that system gets a 
virus that tries to do some outlook automation).

If you wanted to write a Macro, and sign it with a Code Signing Certificate 
from a trusted Certificate Authority we MIGHT be able to make something work, 
but the Outlook automation security is there for a reason and shouldn't be 
messed with (PLUS: I've never written a Python macro for Outlook).  

Note: you can change the Outlook security settings to run Signed Macros 
relatively easy without any security warnings popping up (provided your system 
trusts the CA supplying the Code Signing Certificate and the certificate is not 
expired, etc).  I currently have some VBScript code that will move Mail 
messages to an Exchange public folder and write some data to my SpamAssassin 
server telling SpamAssassin that a mail is "Good" or "Bad" every time a message 
(or multiple messages) are selected and a macro button is pressed in the 
Outlook client (it stops working when I let my certificate expire  ☹ ).

I hope these points help you diagnose this problem further, and or give you 
more ideas on how to automate your task within the Outlook automation security 
framework.

Steven
-Original Message-
From: python-win32  On 
Behalf Of m...@wampenseppl.de
Sent: Sunday, May 15, 2022 3:08 AM
To: python-win32@python.org
Subject: [python-win32] Reading email body from Outlook: Operation aborted

Dear all,

(Transparency note: This has been posted to 
https://python-forum.io/thread-37103.html before)

The following code will print the ReceivedTime as well as the email body on a 
Win11 machine (pywin32 version 304, personal computer):

   import win32com.client

   outlook = 
win32com.client.GetActiveObject('Outlook.Application').GetNamespace("MAPI")
   inbox = outlook.GetDefaultFolder(6).Items
   messages = list(inbox)

   print(messages[0].ReceivedTime)
   print(messages[0].Body)

On a second machine (Win10, same version of pywin32, company device), execution 
will fail:

   PS C:\Users\xxx> & 
C:/Users/xxx/AppData/Local/Programs/Python/Python310/python.exe 
"c:/Users/xxx/outlook.py"
   2021-05-17 16:47:59.781000+00:00
   Traceback (most recent call last):
 File "c:\Users\xxx\outlook.py", line 8, in 
   print(messages[0].Body)
 File 
"C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py",
 line 628, in __getattr__
   ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
   pywintypes.com_error: (-2147467260, 'Operation aborted', None, None)

It can read the ReceivedTime, but not the Body. I think it has to do with 
Outlook security policy as set up on the company device. I've already applied 
the registry keys mentioned at 
https://www.slipstick.com/developer/change-programmatic-access-options/, but 
couldn't see any changed behavior. Also, I can't run Outlook (O365 / V2204) as 
an admin as this will request me to create a new account. I was trying 

Re: [python-win32] [ANN] pywin32 build 304 released

2022-05-02 Thread Steven Manross
Solved.  Huge thanks for pointing me to what I should have read to begin with.  
 ☹

Thank you very much!

In case anyone finds this thread...

Solution was to run:

# cd \python38 (where my python was installed):

# python Scripts/pywin32_postinstall.py -install

... per the link Mark provided (post install script is a little above this 
entry point in the article).

https://github.com/mhammond/pywin32/blob/main/README.md#the-specified-procedure-could-not-be-found--entry-point-not-found-errors

Steven
-Original Message-
From: Mark Hammond  
Sent: Monday, May 02, 2022 4:41 PM
To: Steven Manross ; python-win32@python.org
Subject: Re: [python-win32] [ANN] pywin32 build 304 released

On 3/05/2022 5:31 am, Steven Manross wrote:
> Thanks for the new version!
> 
> Considering I've been on build 227 forever, I tried upgrading my webserver's 
> pywin32 build to 304 with a base of Activestate Python 3.8 (64-bit), and now 
> I'm getting errors in my ASP pages ("500" Server Error), and in ipython 
> (below).

The README has a section dedicated to this - 
https://github.com/mhammond/pywin32/blob/main/README.md#the-specified-procedure-could-not-be-found--entry-point-not-found-errors
 
- tl;dr, you probably have duplicate pywin32 DLLs installed, possibly 
because the different versions were installed using different techniques.

Cheers,

Mark
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] [ANN] pywin32 build 304 released

2022-05-02 Thread Steven Manross
Thanks for the new version!

Considering I've been on build 227 forever, I tried upgrading my webserver's 
pywin32 build to 304 with a base of Activestate Python 3.8 (64-bit), and now 
I'm getting errors in my ASP pages ("500" Server Error), and in ipython (below).

Ive done all the normal things like restarting IIS, restarting the server, etc. 
 Ive also uninstalled, removed site-packages\win32 (and win32com + win32ext) 
and then reinstalled pywin32 (pip install pywin32==304).

Any thoughts would be appreciated.

I have a backup of the server from last night I can restore from if all else 
fails.

Hopefully the ipython output helps understand where the error is (specified 
procedure could not be found).

Please and Thank You for any suggestions,
Steven

Test ASP page:
http://www.w3.org/1999/xhtml;>




Test
<% @ Language = Python %>
<%
Response.Write("Test 2 ")
%>





C:\Users\someuser>ipython
Python 3.8.2 (default, Aug 25 2020, 15:54:26) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import win32api
---
ImportError   Traceback (most recent call last)
 in 
> 1 import win32api

ImportError: DLL load failed while importing win32api: The specified procedure 
could not be found.

-Original Message-
From: python-win32  On 
Behalf Of Mark Hammond
Sent: Monday, May 02, 2022 12:59 AM
To: python-win32@python.org
Subject: [python-win32] [ANN] pywin32 build 304 released

Hi all,
   I'm happy to announce the release of pywin32 build 304. There are a 
number of changes in this release with the significant ones listed below.

Note:
* There are no .exe installers for 32-bit 3.10+ due to Python dropping 
support for bdist_wininst.

* arm64 wheels for 3.10 and 3.11 64bit versions are available on pypi.

Downloads are available at:

   https://github.com/mhammond/pywin32/releases/tag/b304

and via pypi.

For initial support (eg, to ask questions about the release etc), please 
contact this mailing-list (python-win32@python.org).  If you want to 
report a bug, please do so at https://github.com/mhammond/pywin32/issues

As always, thanks to everyone who contributed to this release, both in 
terms of code and reporting bugs - there were a number of new 
contributors which is great to see,

Cheers,

Mark.

Changes:

Since build 303:

* Fixed Unicode issues in the `dde` module (#1861, @markuskimius )

* Add `PRINTER_INFO_6` support for Set/GetPrinter (#1853, @CristiFati)

* Fixed codepage/mojibake issues when non-ascii characters were included
   in COM exceptions raised by Python apps. This should be invisible, but
   might break any workarounds which were used, such as using specific
   encodings in these strings. (#1823, #1833)

* Fixed a bug triggering `win32print.SetJob` to fail due to data type
   (`char*` / `wchar_t*`) mismatch (#1849, @CristiFati)

* Fix eventlog initialization (#1845, #1846, @kxrob)
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] file name contains brackets got converted to %5B and %5D

2022-04-11 Thread Steven Manross
After thinking about this for a bit …  I thought that if the COM object is 
doing this and there’s no way to fix that behavior, you should be able to 
change the file name AFTER the COM object is done, via python like so.

# this works on my W10 PC
import os

# make sure the file handle and or COM object is done locking the DOCX file 
first

os.rename('c:\\somedir\\this%5Bproject_id%5D_date.docx', 
'c:\\somedir\\this[project_id]_date.docx')


Obviously, if the escaping works like Chris suggests, you wouldn’t need this.

HTH

Steven
From: python-win32  On 
Behalf Of Christoph J. Dorner
Sent: Saturday, April 09, 2022 2:52 AM
To: jefferyl...@actgenomics.com; python-win32@python.org
Subject: Re: [python-win32] file name contains brackets got converted to %5B 
and %5D

Hi,

I am not sure If I gto the context, it is hard to understand what you have done 
witht he limited description.

But I guess you passed a filename to a COM object ?
Try to escape the brackets.
And check for problems arising a) from the different notation conventions for 
pathnames and b) differences in unicode treatment in Python an COM.

Regards
Christoph


Am 08.04.2022 um 04:11 schrieb Jeffery Liao (廖弈全):
Hi,

My docx file name contains brackets ([ and ]) and those brackets were changed 
to %5B and %5D after I convert the docx to pdf.

e.g.
before: name_[project_id]_date.docx

after: name_%5Bproject_id%5D_date.pdf

I've searched 
Document.ExportAsFixedFormat
 method (Word) and didn't find any option to change this behavior.

Is there any way to keep the brackets in file name?

Version of Python and pywin32:
Python v3.8.10, pywin32 v300

Best regards
Jeffery


This message contains confidential information and is intended only for the 
individual(s) addressed in the message. If you aren't the named addressee, you 
should not disseminate, distribute, or copy this e-mail. If you aren't the 
intended recipient, you are notified that disclosing, distributing, or copying 
this e-mail is strictly prohibited.
ACT Genomics Holdings Co. Ltd. and its 
subsidiaries



___

python-win32 mailing list

python-win32@python.org

https://mail.python.org/mailman/listinfo/python-win32

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] pywin32 question

2022-03-13 Thread Steven Manross
Ok..  fine…  I was interested so I played with it more.  Here’s what I came up 
with.  Enjoy!

import win32ts

protocols = {
win32ts.WTS_PROTOCOL_TYPE_CONSOLE: "Console",
win32ts.WTS_PROTOCOL_TYPE_ICA: "Citrix",
win32ts.WTS_PROTOCOL_TYPE_RDP: "RDP",
}

session_types = {win32ts.WTSConnected: "Connected",
 win32ts.WTSActive: "Active",
 win32ts.WTSConnectQuery: "Connect Pending",
 win32ts.WTSShadow: "Shadowing another session",
 win32ts.WTSDisconnected: "Disconnected",
 win32ts.WTSIdle: "Idle",
 win32ts.WTSListen: "Listening",
 win32ts.WTSReset: " Resetting",
 win32ts.WTSDown: "Down -- Error",
 win32ts.WTSInit: "Initializing"}

server_name = "someserver.mydomain.com"

ts_connection = win32ts.WTSOpenServer(server_name)

for s in win32ts.WTSEnumerateSessions(ts_connection, 1):
if s['WinStationName'] != "Services" and s['State'] != win32ts.WTSListen:
user = win32ts.WTSQuerySessionInformation(ts_connection, 
s['SessionId'], win32ts.WTSUserName)
if not user:
user = "No one is logged in"

protocol = win32ts.WTSQuerySessionInformation(ts_connection, 
s['SessionId'], win32ts.WTSClientProtocolType)
print(f"Session: {s['SessionId']} - State = {session_types[s['State']]} 
--> User: {user} -- Protocol: {protocols[protocol]}")

win32ts.WTSCloseServer(ts_connection)

output:

Session: 1 - State = Active --> User: myusername -- Protocol: RDP
Session: 2 - State = Connected --> User: No one is logged in -- Protocol: 
Console

HTH

Steven
From: python-win32  On 
Behalf Of Steven Manross
Sent: Sunday, March 13, 2022 8:26 AM
To: Craig R. Matthews ; python-win32@python.org
Subject: Re: [python-win32] pywin32 question

While I don’t have a huge environment to test in, this seems to work remotely 
from my win 10 pc to my Windows Server 2016 which has remote admin RDP enabled… 
 I would assume it’s the same APIs to talk to a full fledged WTS Server.

Kudos to the internet for having the answer already written down for me…  even 
if it was in python 2 syntax (what else should I expect from a post in 
11/2007?).  

https://mail.python.org/pipermail/python-win32/2007-November/006425.html

import win32ts

for s in 
win32ts.WTSEnumerateSessions(win32ts.WTSOpenServer("MYSERVER.MYDOMAIN.COM"),1):
if s['State'] == win32ts.WTSActive:
print(f"Session is active: {s}")

output:

Session is active: {'SessionId': 1, 'WinStationName': 'RDP-Tcp#124', 'State': 0}

take a look at win32ts here:

http://timgolden.me.uk/pywin32-docs/win32ts.html

I am guessing you would also want to use “WTSQuerySessionInformation” as well 
to get more detailed information about the session, but I will leave that to 
you to explore.

I just found this today, so I am no expert on use of this module but it looks 
GREAT and I will likely develop something with it myself eventually.

Steven
From: python-win32 
mailto:python-win32-bounces+steven=manross@python.org>>
 On Behalf Of Craig R. Matthews
Sent: Saturday, March 12, 2022 12:02 AM
To: python-win32@python.org<mailto:python-win32@python.org>
Subject: [python-win32] pywin32 question

I was wondering if there is a way in python to determine the idle time for a 
terminal server session as QUERY USER does.

Also, is there a way to get that python code to run for a server other than the 
one running the code (as in QUERY USER /SERVER:name)?
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] pywin32 question

2022-03-13 Thread Steven Manross
While I don’t have a huge environment to test in, this seems to work remotely 
from my win 10 pc to my Windows Server 2016 which has remote admin RDP enabled… 
 I would assume it’s the same APIs to talk to a full fledged WTS Server.

Kudos to the internet for having the answer already written down for me…  even 
if it was in python 2 syntax (what else should I expect from a post in 
11/2007?).  

https://mail.python.org/pipermail/python-win32/2007-November/006425.html

import win32ts

for s in 
win32ts.WTSEnumerateSessions(win32ts.WTSOpenServer("MYSERVER.MYDOMAIN.COM"),1):
if s['State'] == win32ts.WTSActive:
print(f"Session is active: {s}")

output:

Session is active: {'SessionId': 1, 'WinStationName': 'RDP-Tcp#124', 'State': 0}

take a look at win32ts here:

http://timgolden.me.uk/pywin32-docs/win32ts.html

I am guessing you would also want to use “WTSQuerySessionInformation” as well 
to get more detailed information about the session, but I will leave that to 
you to explore.

I just found this today, so I am no expert on use of this module but it looks 
GREAT and I will likely develop something with it myself eventually.

Steven
From: python-win32  On 
Behalf Of Craig R. Matthews
Sent: Saturday, March 12, 2022 12:02 AM
To: python-win32@python.org
Subject: [python-win32] pywin32 question

I was wondering if there is a way in python to determine the idle time for a 
terminal server session as QUERY USER does.

Also, is there a way to get that python code to run for a server other than the 
one running the code (as in QUERY USER /SERVER:name)?
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] pywin can not access excel file

2021-12-12 Thread Steven Manross
P.S. I also just validated that a non-admin could run the code in ipython with 
a test xlsx, and open the workbook, navigate to a worksheet, and then read a 
value in A1 that I put the words "this is a test" in.


  *   Is User Account Control (UAC) enabled on the PC we are troubleshooting 
with?  That could be causing issues and you may need to troubleshoot that.
  *   Does the non-admin have NTFS permissions to the Excel workbook you are 
working with (my test was just c:\\scripts\\test.xlsx)?  (Can the non-admin 
browse to that file and double click it to open it - just as a test?)
  *   What OS is the PC that we are trying to troubleshoot (W11, W10, W7, W8? 
Or possibly terminal services on a Server OS?) My test was on W10 x64 build 20H2
  *   What version of pywin32 are you running and what version of python are we 
troubleshooting?  Im running Python 3.6

my pywin32 version:

C:\python36>pip freeze| findstr /c:pywin32
WARNING: Ignoring invalid distribution -ffi (c:\python36\lib\site-packages)
pywin32==302
pywin32-ctypes==0.1.2

My guess is that this is more an environmental issue than a python problem, but 
the version info might help in diagnosing this further.

# my test code
import win32com.client as w3c

filename = 'C:scriptsthis.xlsx'

ExcelApp = w3c.DispatchEx("Excel.Application")
ExcelApp.Visible = False
ExcelApp.DisplayAlerts = False
wb = ExcelApp.Workbooks.Open("{0}".format(filename))
worksheet = wb.Worksheets[0]
worksheet.Range("A1").Value

# Ipython output:

In [5]: worksheet.Range("A1").Value
Out[5]: 'this is a test'


P.S. Im also a fan of F-strings...

  wb = ExcelApp.Workbooks.Open(f"{filename}")

OR more simply

  wb = ExcelApp.Workbooks.Open(filename)

HTH

Steven
From: python-win32  On 
Behalf Of Steven Manross
Sent: Sunday, December 12, 2021 6:00 PM
To: Tamara Abugharbieh ; 
python-win32@python.org
Subject: Re: [python-win32] pywin can not access excel file

Is this a typo on the email or is your production code really referencing 
filename and fileName?

You need to reference the variable name using the same casing in both places 
(if this is not a typo in your email example).

P.S. I don't think you need the 4 backslashes..  2 usually does the trick, but 
there's nothing from stopping it from working using 4 backslashes.


import win32com.client as w3c



# lowercase

filename = 
'C:AppBackendpublicMSB_202111SYB_10_7_V1.xlsx'

ExcelApp = w3c.DispatchEx("Excel.Application")
ExcelApp.Visible = False
ExcelApp.DisplayAlerts = False
# mixed case
wb = ExcelApp.Workbooks.Open("{0}".format(fileName))


From: python-win32  On 
Behalf Of Tamara Abugharbieh
Sent: Sunday, December 12, 2021 1:32 AM
To: python-win32@python.org
Subject: [python-win32] pywin can not access excel file

Hi,

We are using winpy32 to automate excel applications using python. The python 
script will be used by users with no administrator privileges, and in this 
case, we are getting the following error:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft 
Excel', \"Microsoft Excel cannot access the file 
'C:AppBackendpublicMSB_202111SYB_10_7_V1.xlsx'. There 
are several possible reasons: The file name or path does not exist. The file is 
being used by another program. The workbook you are trying to save has the same 
name as a currently open workbook.\", 'xlmain11.chm', 0, -2146827284)

Things to note:

  1.  The file does exist
  2.  The file is not being used by another program
  3.  The path is correct
  4.  The python script is being successfully used by users with administrative 
privileges

Please find bellow the method I am using to open the excel file:


import win32com.client as w3c



filename = 
'C:AppBackendpublicMSB_202111SYB_10_7_V1.xlsx'

ExcelApp = w3c.DispatchEx("Excel.Application")
ExcelApp.Visible = False
ExcelApp.DisplayAlerts = False
wb = ExcelApp.Workbooks.Open("{0}".format(fileName))

Appreciate your help.

Best,
Tamara

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] pywin can not access excel file

2021-12-12 Thread Steven Manross
Is this a typo on the email or is your production code really referencing 
filename and fileName?

You need to reference the variable name using the same casing in both places 
(if this is not a typo in your email example).

P.S. I don't think you need the 4 backslashes..  2 usually does the trick, but 
there's nothing from stopping it from working using 4 backslashes.


import win32com.client as w3c



# lowercase

filename = 
'C:AppBackendpublicMSB_202111SYB_10_7_V1.xlsx'

ExcelApp = w3c.DispatchEx("Excel.Application")
ExcelApp.Visible = False
ExcelApp.DisplayAlerts = False

# mixed case
wb = ExcelApp.Workbooks.Open("{0}".format(fileName))


From: python-win32  On 
Behalf Of Tamara Abugharbieh
Sent: Sunday, December 12, 2021 1:32 AM
To: python-win32@python.org
Subject: [python-win32] pywin can not access excel file

Hi,

We are using winpy32 to automate excel applications using python. The python 
script will be used by users with no administrator privileges, and in this 
case, we are getting the following error:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft 
Excel', \"Microsoft Excel cannot access the file 
'C:AppBackendpublicMSB_202111SYB_10_7_V1.xlsx'. There 
are several possible reasons: The file name or path does not exist. The file is 
being used by another program. The workbook you are trying to save has the same 
name as a currently open workbook.\", 'xlmain11.chm', 0, -2146827284)

Things to note:

  1.  The file does exist
  2.  The file is not being used by another program
  3.  The path is correct
  4.  The python script is being successfully used by users with administrative 
privileges

Please find bellow the method I am using to open the excel file:


import win32com.client as w3c



filename = 
'C:AppBackendpublicMSB_202111SYB_10_7_V1.xlsx'

ExcelApp = w3c.DispatchEx("Excel.Application")
ExcelApp.Visible = False
ExcelApp.DisplayAlerts = False
wb = ExcelApp.Workbooks.Open("{0}".format(fileName))

Appreciate your help.

Best,
Tamara

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Outlook Add-In Demo Question ... A runtime error occurred during the loading of the com add-in

2021-12-09 Thread Steven Manross
Thanks for verifying!

Mine is a Desktop version...  not 365 (installed with Product Key not 
subscription as part of Office Professional Plus 2019)

Steven
-Original Message-
From: python-win32  On 
Behalf Of Tim Roberts
Sent: Thursday, December 09, 2021 11:27 AM
To: python-win32 
Subject: Re: [python-win32] Outlook Add-In Demo Question ... A runtime error 
occurred during the loading of the com add-in

Steven Manross wrote:
> Correct me if I am wrong...  but Office 2010+ comes in 64-bit and 32-bit 
> versions.  I know that 2019 definitely does.

Both are available, but until Office 2019 the 32-bit version was the default, 
so that's what virtually everyone has.


> Providing he matches his Python architecture (32 or 64) to his Office 
> application architecture (32 or 64), it should work unless that code has 
> issues working in 64-bit mode?  I haven’t tried this myself in this 
> particular case, as I've always installed 32-bit Office apps.

Right.


> Its possible that my Office 2019 install doesn’t have the correct components 
> or APPIDs or CLSIDs installed (even if I matched the python and office 
> architectures) as I searched for them and couldn’t find them in the native 
> x64 and x86 registry subkeys:
>
> * HKEY_CLASSES_ROOT
> * HKLM\Software\Classes
> * OR HKLM\Software\Wow6432Node\Classes

Is this the desktop versions or the Office 365 versions?  There are 
differences.

-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] Outlook Add-In Demo Question ... A runtime error occurred during the loading of the com add-in

2021-12-08 Thread Steven Manross
Correct me if I am wrong...  but Office 2010+ comes in 64-bit and 32-bit 
versions.  I know that 2019 definitely does.

Providing he matches his Python architecture (32 or 64) to his Office 
application architecture (32 or 64), it should work unless that code has issues 
working in 64-bit mode?  I haven’t tried this myself in this particular case, 
as I've always installed 32-bit Office apps.  

As well, I just tried to run the addin code with my 64-bit python and it told 
me " Library not registered".  

C:\scripts>python outlookaddin.py
Traceback (most recent call last):
  File "outlookaddin.py", line 38, in 
gencache.EnsureModule('{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}', 0, 2, 1, 
bForDemand=True) # Office 9
  File "C:\Python36\lib\site-packages\win32com\client\gencache.py", line 605, 
in EnsureModule
bBuildHidden=bBuildHidden,
  File "C:\Python36\lib\site-packages\win32com\client\gencache.py", line 319, 
in MakeModuleForTypelib
bBuildHidden=bBuildHidden,
  File "C:\Python36\lib\site-packages\win32com\client\makepy.py", line 257, in 
GenerateFromTypeLibSpec
tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
pywintypes.com_error: (-2147319779, 'Library not registered.', None, None)

Its possible that my Office 2019 install doesn’t have the correct components or 
APPIDs or CLSIDs installed (even if I matched the python and office 
architectures) as I searched for them and couldn’t find them in the native x64 
and x86 registry subkeys:

* HKEY_CLASSES_ROOT
* HKLM\Software\Classes
* OR HKLM\Software\Wow6432Node\Classes

These 2 IDs  (Maybe only there in older office versions? Not Sure):
{00062FFF---C000-0046}
{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}

The Library Not registered is what I would expect if you were running into a 
64-bit python and 32-bit application (or vice versa) problem as the script just 
wouldn't find the needed library.  I see this a lot with ODBC access to MS SQL 
Server, Sybase, et al (not having the correct architecture's drivers installed 
to perform the operation I am expecting to work) in VBScript, Perl and Python.

HTH

Steven
-Original Message-
From: python-win32  On 
Behalf Of Tim Roberts
Sent: Wednesday, December 08, 2021 1:43 PM
To: python-win32 
Subject: Re: [python-win32] Outlook Add-In Demo Question ... A runtime error 
occurred during the loading of the com add-in

Vernon D. Cole wrote:
> Most likely, you are running a 64  bit version of Python.
> Due to Windows restrictions, only 32 bit programs can talk to each other.

That comment demands clarification, because as stated it is quite misleading.

The issue here is that a 32-bit application can only load 32-bit DLLs. Outlook 
2016 is a 32-bit application, so when it as a COM client tries to load an 
in-process COM server (that is, his add-in), the COM server DLL must also be 
32-bit.

There are many, many ways that 32-bit and 64-bit programs can talk to each 
other.  This is a very specific instance.

--
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] mail Sensitivity doesn't work as expected(can not set the sensitivity label)

2021-11-17 Thread Steven Manross
As best I remember, Microsoft considers the programming of Mail tasks (and most 
Outlook automation) as a security risk/issue, and limits your access to certain 
parts because so many people (malware writers) wrote stuff to programmatically 
abuse Outlook for unsavory (Evil?!?) purposes.

However, fear not...  I have successfully and programmatically used something 
called Outlook Redemption to unlock these secured areas of Outlook when I have 
needed to do something Microsoft didn't allow you to programmatically perform 
in the past (I'm not the author of the software nor do I get a commission for 
referring people to it).  I don't think I even have that software loaded 
anymore.

https://www.dimastr.com/redemption/home.htm

There is a "developer version" usable for free, but it is a saleable product.  
Read the license, use it at your own risk (since ultimately Microsoft locked 
certain aspects of Outlook off for a reason - and loading this product would in 
essence bypass those restrictions).  The author of Redemption has great KB 
articles and examples, but most of my programming with this product was in 
VBScript, so I'm not going to be able to share examples in Python.  A lot of 
what I was doing with the module was reading messages out to files or querying 
particular MAPI attributes for use with a Microsoft Exchange-based SpamAssassin 
filter - or - Monitor a mailbox for incoming emails and perform some task with 
the messages in a separate system (provided the message met certain criteria).  
The product has also been on the market for 10+ years, so it's a very mature 
product (NOT like a 1.0 or 0.9 version).

HTH

Steven
From: python-win32  On 
Behalf Of Victor Liu
Sent: Wednesday, November 17, 2021 7:31 AM
To: python-win32@python.org
Subject: [python-win32] mail Sensitivity doesn't work as expected(can not set 
the sensitivity label)

Hi guys,
Gratitude to all the work of the library. I am trying to use it to send out 
some emails, but I have encountered this issue which might be a bug. It can be 
represented by this minimum working example.

import win32com.client



outlook = win32com.client.Dispatch('outlook.application')

mail = outlook.CreateItem(0)

mail.To = 'vic...@example.com'

mail.Subject = 'Sample Email'

mail.HTMLBody = 'This is HTML Body'

mail.Body = "This is the normal body"

mail.CC = 'vic...@example.com'

mail.Sensitivity = 1

mail.Send()
This works well expect the mail.sensitivity =1 part, so it pops up a window to 
set the sensitivity label(Bear in mind, not all outlook has set up this 
restriction).
[Image removed by sender. 
image]
This makes the process is impossible to automate.
My understanding is mail.sensitivity =1 is for that Azure label. Please let me 
know if I missed something.
Thank you all in advance.
Victor
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] returning #N/A to Excel via UDF

2021-11-17 Thread Steven Manross
While I don’t have any useful suggestions here…  I thought I would link the 
thread I found in the xlwings github thread that the author looks to have been 
working on with them already.

https://github.com/xlwings/xlwings/issues/776

HTH

Steven
From: python-win32  On 
Behalf Of Sébastien de Menten
Sent: Wednesday, November 17, 2021 1:12 AM
To: python-win32 
Subject: [python-win32] returning #N/A to Excel via UDF

I would like to return #N/A values to excel via an UDF written in python (via 
xlwings)

Returning a `VARIANT(pythoncom.VT_ERROR, 2042)` from the UDF results in an 
empty cell.
Is there within pywin32/pythoncom an equivalent of VBA `CVErr(xlErrNA)` ?

Sébastien
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


[python-win32] Access Denied on Eventlogs - possible solution(s)

2021-09-17 Thread Steven Manross
Howdy.

I replied offline to the author earlier in my day about what might be the 
problem he is running into (I was in digest mode until today and couldnt just 
reply to the thread - apologies), but played around with this script a little 
today and seem to have something that can pass credentials to a call for 
eventlogs and wanted to share with the list (now that I had a working sample).

Based on the API that was available for running searches on remote computers, I 
had to output the data into XML and did not parse the XML (a task which I leave 
to the original author of this thread -- using something like lxml).

However, Hopefully this helps the original author see how he might be able to 
inject credentials into their script to get what they need.

It is worthy of note that the original poster's script worked fine on my test 
systems (with Remote Scripting UAC disabled) which might suggest that there's a 
problem with how the remote server is configured and maybe "Allowing Remote 
Scripts to Bypass UAC" is the solution to their whole problem...  See here:


https://docs.microsoft.com/en-us/troubleshoot/windows-server/windows-security/user-account-control-and-remote-restriction

Kudos to the pywin32 maintainers and the members of this list for their input.  
I hope this minor script helps someone.

# ---
# tested using python 3.6.3 on W10x64 with domain admin credentials tested in 
the script

import win32evtlog # requires pywin32 pre-installed
import time

user = "someuser" # your windows username
domain = "SOMEDOMAIN" # your windows domain name (or possibly computername)
passwd = "reallysecurepassword" # your unencrypted password
server = 'IP_OR_FQDN' # name of the target computer to get event logs

try:
logtype = 'System' # 'Application' # 'Security'
sess_handle = win32evtlog.EvtOpenSession(Login=(server, user, domain, 
passwd, win32evtlog.EvtRpcLoginAuthDefault),
Timeout=0,
Flags=0)

query_flags = win32evtlog.EvtQueryReverseDirection | 
win32evtlog.EvtQueryChannelPath

# while I get "*" (all the logs), this thread seems to suggest you could 
limit it..  however, their syntax didn't work for me
# 
https://stackoverflow.com/questions/29827769/get-an-event-object-from-win32evtlog-evtquery-results
log_handle = win32evtlog.EvtQuery(logtype, query_flags, "*", sess_handle)

x = 0
count = 10   # get x events per query
events = win32evtlog.EvtNext(ResultSet=log_handle, Count=count,Timeout=0, 
Flags=0)
while events:
for event in events:
x += 1
print(f'b4 render: {x} --> {event}')
print (f'Event Data: {win32evtlog.EvtRender(event, 
Flags=win32evtlog.EvtRenderEventXml)}')

events = win32evtlog.EvtNext(ResultSet=log_handle, 
Count=count,Timeout=0, Flags=0)
time.sleep(5)

except Exception as e:
print(f"Excepted with: {e}")



# minor excerpt of output:
b4 render: 240 --> 
Event Data: 703604000x8080296223Systemsomecomuter.somewhere.comWMI Performance Adapterstopped77006D006900410070005300720076002F003100
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


[python-win32] Calling Dispatch - Error -2147221005

2021-07-20 Thread Steven Manross
Seems like you have the class string invalid…

“Outlook Application” should read “Outlook.Application”

Note the period.  

And then of course, you need Outlook installed, and the correct 32-bit or 
64-bit version of Outlook for your python version.

HTH and Enjoy

Steven
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


[python-win32] How to copy an image using win32clipboard

2020-12-01 Thread Steven Manross
Based on reading 
http://timgolden.me.uk/pywin32-docs/win32clipboard__GetClipboardData_meth.html 
I would suggest that getting image data from the clipboard isn't implemented 
yet, but I do not know that for sure as I don't know when that document was 
updated.

However, this python code seems to get text data just fine.

import win32clipboard


win32clipboard.OpenClipboard()
var = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

print(var)

I would also point out that it seems that the "CloseClipboard" is incredibly 
important as it seems that python takes an exclusive lock on the clipboard 
while the Clipboard is Opened.

HTH

Steven
---
Date: Tue, 1 Dec 2020 11:00:52 +
From: Pranav Gadre 
To: "python-win32@python.org" 
Subject: [python-win32] How to copy an image using win32clipboard
Message-ID:



Content-Type: text/plain; charset="windows-1252"

Hello,

When we take a snip on windows OS, it automatically goes to clipboard. I want 
to access any copied image using win32clipboard. How do I do that?
Please check this for more reference: Closed 
issue
Thank you and pardon me for any missing things as I?m new to this mailing list.
Regards,
Pranav



___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


Re: [python-win32] IIS and ASP: If blocks that span multiple code blocks

2020-11-03 Thread Steven Manross
Thanks for the reply!

Just an FYI...  This VBScript/ASP code/behavior is probably 10+ years old.

I've already started adapting the python code understanding that it wasn’t 
likely possible (or was going to take a major RFE that wasn't likely coming any 
time soon) - and it all works well now.

I hope this helps someone searching the internet for answers to how Python & 
VBScript in ASP behave differently.

I don’t put it past Microsoft to give their technologies an advantage over 
other scripting languages when it comes to things like this.

Kudos to everyone's work/documentation on python-win32 and the pywin32 
libraries.  This is amazing work, and I super-appreciate it all!  

The coding to translate a VBScript project was pretty seamless, except when it 
came to "Scripting.Dictionary" objects (some weird edge cases on manipulating 
items after they were created), and in that case, I just converted to python 
dictionaries since they are SO flexible and come OOTB without need for COM 
objects (like in VBScript).

HTH someone

Steven
-Original Message-
From: Mark Hammond  
Sent: Monday, November 02, 2020 3:50 PM
To: Steven Manross ; python-win32@python.org
Subject: Re: [python-win32] IIS and ASP: If blocks that span multiple code 
blocks

IIS/ASP sends Python different strings to evaluate, and Python evaluates them 
individually. It's much like wanting Python code such as:

if foo:
   bar()

To be handled in Python by using:

 >>> exec("if foo:\n")
 >>> exec("  bar()\n")

Which doesn't work.

The semantics are largely defined by the "Active Scripting" 
specifications. I haven't kept up with that recently, so it's possible there 
have been enhancements to that spec which might make this possible, but if 
there were, they would have been targeted at making languages offered directly 
by MS better than Python.

So I'm afraid that I think you are out of luck.

Cheers,

Mark

On 2/11/2020 12:12 pm, Steven Manross wrote:
> I was wondering if there's any way to support this style of coding in 
> ASP/Python.
> 
> This works in VBScript (but I'm trying to remove all my VBScript), but I seem 
> to be getting hit by the fact that each block of code is being analyzed as a 
> single block of code and the "if" not being able to span multiple code blocks.
> 
> #VBScript
> <%
> If This = "THAT" Then
>  Response.Write("BEFORE")
> %>
>  This does == THAT
>   <%
>  Response.Write("AFTER")
> End If
> %>
> 
> What I am trying to show you is that in VBScript, an IF block can span 
> the multiple code regions (<% code %>) and conditionally display the 
> HTML in between the IF and END IF if the condition matches
> 
> Note that in VBScript if This = "THAT", this VBScript would display:
> 
> BEFORE
> This does == THAT
>   *** whatever the include file displayed AFTER
> 
> And of course, if This <> "THAT" it wouldn't display anything from above!
> 
> However in Python, and a similarly structured code-block:
> 
> #Python
> <%
> if This == "THAT":
>  Response.Write("BEFORE")
> %>
>  This does == THAT
>   <%
> Response.Write("AFTER")
> %>
> 
> In python, We would get (if This == "THAT"):
> 
> BEFORE
> This does == THAT
>   *** and whatever the include file displayed (if the include file had 
> no additional logic to filter the data) AFTER
> 
> However, in python, we would get (if This != "THAT"):
> 
> This does == THAT
>   *** and whatever the include file displayed (if the include file had 
> no additional logic to filter the data) AFTER
> 
> Lastly, if I indent the Response.Write("AFTER") in this second code block 
> to try and span the code block to the same conditional started in the first 
> code block, I get a syntax error like this:
> 
> unexpected indent
> /folder/somefile.asp, line ###
>  Response.Write("AFTER")
> ---^
> 
> is there any way around this without doing a lot of other if blocks in 
> each section of <% code %>
> 
> It sounds like an RFE to me (and probably not an easy one), but maybe I'm 
> missing something?
> 
> IIS on W2016 (most recent patches)
> Activestate Python: 3.8.2
> pywin32==227
> 
> Please and Thank You,
> Steven
> ___
> python-win32 mailing list
> python-win32@python.org
> https://mail.python.org/mailman/listinfo/python-win32
> 

___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32


[python-win32] IIS and ASP: If blocks that span multiple code blocks

2020-11-01 Thread Steven Manross
I was wondering if there's any way to support this style of coding in 
ASP/Python.

This works in VBScript (but I'm trying to remove all my VBScript), but I seem 
to be getting hit by the fact that each block of code is being analyzed as a 
single block of code and the "if" not being able to span multiple code blocks.

#VBScript
<%
If This = "THAT" Then
Response.Write("BEFORE")
%>
This does == THAT

<%
Response.Write("AFTER")
End If
%>

What I am trying to show you is that in VBScript, an IF block can span the 
multiple code regions (<% code %>) and conditionally display the HTML in 
between the IF and END IF if the condition matches

Note that in VBScript if This = "THAT", this VBScript would display:

BEFORE
This does == THAT
 *** whatever the include file displayed 
AFTER

And of course, if This <> "THAT" it wouldn't display anything from above!

However in Python, and a similarly structured code-block:

#Python
<%
if This == "THAT":
Response.Write("BEFORE")
%>
This does == THAT

<%
Response.Write("AFTER")
%>

In python, We would get (if This == "THAT"):

BEFORE
This does == THAT
 *** and whatever the include file displayed (if the include file had no 
additional logic to filter the data)
AFTER

However, in python, we would get (if This != "THAT"):

This does == THAT
 *** and whatever the include file displayed (if the include file had no 
additional logic to filter the data)
AFTER

Lastly, if I indent the Response.Write("AFTER") in this second code block 
to try and span the code block to the same conditional started in the first 
code block, I get a syntax error like this:

unexpected indent
/folder/somefile.asp, line ###
Response.Write("AFTER")
---^

is there any way around this without doing a lot of other if blocks in each 
section of <% code %>

It sounds like an RFE to me (and probably not an easy one), but maybe I'm 
missing something?

IIS on W2016 (most recent patches)
Activestate Python: 3.8.2
pywin32==227

Please and Thank You,
Steven
___
python-win32 mailing list
python-win32@python.org
https://mail.python.org/mailman/listinfo/python-win32