Win32Com connection failure to Autocad via Python - python

I need to connect and control AutoCAD via COM interface. For this purpose, I use Python. In my first trial with a very basic snippet(1), I got an error. The code is:
import win32com.client
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument
doc.Utility.Prompt("Hello from Python\n")
and when I try to run it, I get this:
Traceback (most recent call last):
File "C:\Users\SBYSMR10\Desktop\recipe-440493-1.py", line 2, in <module>
acad = win32com.client.Dispatch("AutoCAD.Application")
File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 108, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 85, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2147221005, 'Invalid class string', None, None)
I have Python 2.6 and AutoCAD LT 2009 installed. I searched through the net for a solution but couldn't find any. So could you help me fix this issue?
(1) Code taken from #Tom Haws' blog.

AutoCAD LT versions doesn't support automation (discussion in Autodesk group).
If you'll be able to install full AutoCAD version, I'd suggest you to use comtypes package. With win32com you can't add entities to document, because AutoCAD requires VARIANTs with the typecodes VT_ARRAY | VT_I2 or VT_ARRAY | VT_R8 for parameters, e.g. InsertionPoint.
See examples in comtypes documentation

Related

How to write an array tag in a VARIANT structure on an OpenOPC server

I'm trying to communicate with an OPC DA server and need to write in a tag which is in an array format. We can connect with a simulation server, read tags (int, real, array) and write tags (int, real, str). The problem comes when we need to write in an array tag. The developper of the OpenOPC library (Barry Barnreiter) recommand to use a VARIANT variable because OPC "expect to see a Windows VARIANT structure when writing complex objects such as arrays".
I did install Pywin32 (build 217) as suggested here.
I tried to send a simple integer instead of an array in a VARIANT structure.
Here's the code:
from win32com.client import VARIANT
import pythoncom
import OpenOPC
opc_local = OpenOPC.open_client()
opc_local.connect('Matrikon.OPC.Simulation','localhost')
values = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
w = opc_local.write(('Bucket Brigade.ArrayOfReal8', values))
print(w)
Here's the error that we get when the line with opc_local.write gets executed:
AttributeError: 'module' object has no attribute 'VARIANT'
Here's the entire traceback:
runfile('C:/Users/nadmin/Downloads/sanstitre0.py', wdir='C:/Users/nadmin/Downloads')
Traceback (most recent call last):
File "<ipython-input-5-6799f41ab928>", line 1, in <module>
runfile('C:/Users/nadmin/Downloads/sanstitre0.py', wdir='C:/Users/nadmin/Downloads')
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 95, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/nadmin/Downloads/sanstitre0.py", line 14, in <module>
w = opc_local.write(('Bucket Brigade.ArrayOfReal8', values))
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\Pyro\core.py", line 381, in __call__
return self.__send(self.__name, args, kwargs)
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\Pyro\core.py", line 456, in _invokePYRO
return self.adapter.remoteInvocation(name, Pyro.constants.RIF_VarargsAndKeywords, vargs, kargs)
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\Pyro\protocol.py", line 497, in remoteInvocation
return self._remoteInvocation(method, flags, *args)
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\Pyro\protocol.py", line 572, in _remoteInvocation
answer.raiseEx()
File "C:\Users\nadmin\AppData\Local\Continuum\anaconda2\lib\site-packages\Pyro\errors.py", line 72, in raiseEx
raise self.excObj
And here's the configuration of the computer:
Windows 10
Python 2.7
Pyro 3.16
Pywin32 Build 223
OpenOPC 1.3.1 win32-py27
You have to change your line opc_local = OpenOPC.open_client() for opc_local = OpenOPC.client(). This will make you connect directly to the OPC server, as opposed to using the OpenOPC Gateway Service.
The VARIANT structure is not included inside the Gateway Service exe. Note that the Gateway Service exe is it's own frozen Python distribution. Thus it only includes the Python modules inside it that it needs to run and nothing else. So by avoiding using the Gateway Service you should not have this problem since you'll be executing your code entirely using the Python distribution that you installed yourself on your PC.
According to Python COM server throws 'module' object has no attribute 'VARIANT', the VARIANT class was introduced in Pywin32 build 217.
As you have included in your post that you have Pywin32 Build 223, this should not be a problem. But to be sure, from this list of available downloads: Home / pywin32 / Build 217, I would specifically select pywin32-217.win-amd64-py2.7.exe.
If that doesn't work, I would suggest checking the source of the configuration you listed; Do you only have one version of python installed? Perhaps you have multiple Python IDEs that could get mixed up? These are some common cases that can cause confusion in fixing bugs.
You need to upgrade the python to 3.9 and Pywin32 to Build 302. In addition, you need to install the OpenOPC-Python3x 1.3.1.

'No such interface supported' when using .NET 6.0 COM object in python 3.9

I have a .NET 6.0 COM library that I am trying to use with Python 3.9. I additionally wrote an idl file to create a tlb and registered the COM object using regsvr32. The registration seems fine as the registry entries look good and I can also use the object with other COM clients such as Excel and LabWindows. However, when using the COM object in a python script I get the following errors:
Traceback (most recent call last):
File "path\Python39\site-packages\win32com\client\dynamic.py", line 81, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
line 5, in Init
test = win32com.client.Dispatch("ComTest")
File "path\Python39\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "path\Python39\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "path\Python39\site-packages\win32com\client\dynamic.py", line 83, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147467262, 'No such interface supported', None, None)
My code looks like this:
Python:
import win32com.client
def Init():
test = win32com.client.Dispatch("ComTest")
test.SomeMethod(1, 2, "test")
if __name__ == "__main__":
Init()
C#:
Interface
[ComVisible(true)]
[Guid(AssemblyInfo.InterfaceGuid)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComTest
{
public double SomeMethod(double param1, double param2, string param3);
}
Class
[ComVisible(true)]
[Guid(AssemblyInfo.ClassGuid)]
[ProgId("ComTest")]
public class ComTest : IComTest
{
public double SomeMethod(double param1, double param2, string param3)
{
// implementation
}
}
I first thought it might be some issue with different bit versions but that does not seem to be the problem either. I tried installing a 32 bit version of python and testing it with that but I still got the same error. Does someone know what might cause the problem? Thanks for your help.

Issues trying to Dispatch a SASEGObjectModel COM Object with Python using win32com

I'm trying to use pywin32 to manipulate SAS Enterprise Guide using Python. But I'm running into some errors. I've tried both Dispatch and EnsureDispatch, but both return the same error:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 89, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\xxxxxxx\Desktop\test.py", line 4, in <module>
sas = EnsureDispatch('SASEGObjectModel.Application.7.1')
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\gencache.py", line 527, in EnsureDispatch
disp = win32com.client.Dispatch(prog_id)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)
(This is using EnsureDispatch, the error using Dispatch is almost the same, only without the 2nd and 3rd lines after the second traceback).
Also, I've tried running makepy (from the same lib) to see what it would return, and I get the following message:
Could not locate a type library matching 'SASEGObjectModel.Application.7.1'
If I try doing it using vbs, using the following code:
Set app = CreateObject("SASEGObjectModel.Application.7.1")
WScript.echo app.Name
It shows a message box with 'Enterprise Guide' written, showing that the object is available to the system.
I've tried asking for help over SAS Support Community, and after many interesting suggestions, I still couldn't solve the issue. But one thing that I hadn't tried, and ended up working, was install a fresh python installation (Not Anaconda), installing PyWIN and it simply worked.

SASL-GSSAPI on windows fails during bind

I have tried below lined of code on RHEL it works so great. On Linux I just have to acquire the Kerberos ticket.
mport ldap
import ldap.sasl
conn=ldap.initialize('ldap://auto.test-auto.com',trace_level=2)
conn.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3)
conn.set_option(ldap.OPT_REFERRALS,0)
sasl = ldap.sasl.gssapi()
conn.sasl_interactive_bind_s('', sasl)
Then I copied same thing in to a windows 2k3 server where ActivePython-2.7","python-ldap-2.4.10", "openssl-0.9.8o","setup-sasl-1.5.27" are installed.
Traceback (most recent call last):
File "C:\susanta\test-sasl.py", line 10, in <module>
conn.sasl_interactive_bind_s('', sasl)
File "C:\Python27\lib\site-packages\ldap\ldapobject.py", line 229, in sasl_interactive_bind_s
return self._ldap_call(self._l.sasl_interactive_bind_s,who,auth,RequestControlTuples(serverctrls),RequestControlTuples(clientctrls),sasl_flags)
File "C:\Python27\lib\site-packages\ldap\ldapobject.py", line 99, in _ldap_call
result = func(*args,**kwargs)
LOCAL_ERROR: {'desc': 'Local error'}
Could some one help me out?
Are you using Cyrus SASL as backend? If so, it compiled against MIT or Heimdal. You don't have access to the TGT. Search for registry key: session key tgt.
But Cyrus SASL is not really usable on Windows if you use GSS-API unless you try Kerberos for Windows.

OSQA and Django 1.3.1. error when posting text with URL

first of all: I am not a python programmer, i just want to run default instalation of OSQA on linux hosting. My hosting provider installed it for me, and OSQA is working with ony one (but serious) error - if i try to post question/answer/comment with URL in text (http://www.whatever.com/whatever) - the empty post is added (no text at all), and this error appears in log :
/data/web/slovensko20.sk/web/forum/models/node.py TIME: 2012-02-05 23:29:14,944 MSG: node.py:_as_markdown:34 Caught exception 'module' object has no attribute 'etree' in markdown parser rendering Answer 'module' object has no attribute 'etree':\s Traceback (most recent call last):
File "/data/web/slovensko20.sk/web/forum/models/node.py", line 30, in _as_markdown
return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
File "build/bdist.linux-x86_64/egg/markdown/__init__.py", line 396, in markdown
File "build/bdist.linux-x86_64/egg/markdown/__init__.py", line 287, in convert
File "build/bdist.linux-x86_64/egg/markdown/treeprocessors.py", line 289, in run
text), child)
File "build/bdist.linux-x86_64/egg/markdown/treeprocessors.py", line 110, in __handleInline
data, patternIndex, startIndex)
File "build/bdist.linux-x86_64/egg/markdown/treeprocessors.py", line 237, in __applyPattern
node = pattern.handleMatch(match)
File "/data/web/slovensko20.sk/web/forum/markdownext/mdx_urlize.py", line 27, in handleMatch
el = markdown.etree.Element("a")
AttributeError: 'module' object has no attribute 'etree'
I tried to google it, but no luck.
OSQA is Fantasy Island (v0.9.0) Beta 3, Django is in version 1.3.1 afaik.
Thanks for any help!
The Python-Markdown new version seems move etree/AtomicString to markdown.util, So you can try this workaround, modify mdx_urlize.py
try:
from markdown.util import etree
## replace markdown.etree with just etree
#el = markdown.etree.Element("a")
el = etree.Element("a")
## replace markdown.AtomicString with markdown.util.AtomicString
#el.text = markdown.AtomicString(text)
el.text = markdown.util.AtomicString(text)
You may also see this patch as reference.

Categories