I am trying to create python classes to be used in Excel, taking references from Python: Programming on Win32.
Currently:
Python script (win32comLibrary.py)
class PythonUtilities:
_public_methods_ = [ "SplitString" ]
_reg_progid_ = "PythonDemos.Utilities"
_reg_clsid_ = "{AF272547-D5BC-4452-852E-3F8746672097}"
def SplitString(self, val, item = None):
import string
if item!=None: item = str(item)
return string.split(str(val), item)
if __name__== "__main__":
print("Registering COM server...")
import win32com.server.register
win32com.server.register.UseCommandLine(PythonUtilities)
Excel VBA
Sub test()
Set PythonUtils = CreateObject("PythonDemos.Utilities")
response = PythonUtils.SplitString("Hello From VB", " ")
For Each Item In response
MsgBox Item
Next Item
End Sub
Questions:
(a) at the reponse = ... line, there is a runtime error '-2147467259 (80004005)': Unexpected Python Error: Traceback (most recent call last): File .....
(b) when i typed python win32comLibrary.py --unregister in cmd, it returned Registering COM server...Traceback (most recent call last): File "win32comLibrary.py", line 19, in (module) import win32com.server.register ImportError: No module named win32com.server.register
I am currently using anaconda (spyder) and have installed pywin32. Invoking win32com.client methods from Python don't seem to throw any error.
Any assistance would be appreciated.
I have managed to solve the issue - just to close this off. Not sure if its the difference between older versions of python and 3.x but string.split(str(val), item) doesn't seem to work anymore. Instead, I have changed the return statement to return val.split(item). Oversight on my part - apologies.
Related
I can call functions in my dll from python.
When I call a dll function that does a callback to my python code it fails.
It there some sort of mutex blocking my callback?
from ctypes import *
import _ctypes
#CFUNCTYPE(None)
def Test():
print ("Test here")
return
def SetUpDll():
print ("Setting read / write callback functions...")
windll.ClaRUN.AttachThreadToClarion(1)
MyDll = CDLL('IC2_CommsServer.dll')
SetTestFunc = getattr(MyDll, "SETTESTFUNC#Fl")
SetTestFunc (Test)
CallTestFunc = getattr(MyDll, "CALLTESTFUNC#F")
CallTestFunc()
_ctypes.FreeLibrary(MyDll._handle)
_ctypes.FreeLibrary(windll.ClaRUN._handle)
print ("Done.")
SetUpDll()
C:\Users\Derek\anaconda3_32\python.exe Z:/ps_IC2_dll/ps_IC2_dll.py
Setting read / write callback functions...
Traceback (most recent call last):
File "Z:/ps_IC2_dll/ps_IC2_dll.py", line 48, in <module>
SetUpDll()
File "Z:/ps_IC2_dll/ps_IC2_dll.py", line 40, in SetUpDll
CallTestFunc()
OSError: exception: access violation writing 0x009EF77C
Process finished with exit code 1
First, on Windows, the ctypes uses win32 structured exception handling to prevent crashes from general protection faults when functions are called with invalid argument values.
You have a bad call for this line of code:
CallTestFunc = getattr(MyDll, "CALLTESTFUNC#F")
Try to review your code, then see if the problem is from ps_IC2_dll.py build area.
Thanks to CristiFati who provided half of the answer.
This code now works, note that the clarion dll functions are now prototyped as ,C
A nice side effect is that the function names loose the "#F" suffix and so the code is simpler.
from ctypes import *
import _ctypes
#CFUNCTYPE(None)
def Test():
print ("Test here")
return
def SetUpDll():
print ("Setting read / write callback functions... Ptr=", sizeof(c_void_p), "bytes")
assert sizeof(c_void_p) == 4
ClaRTL = CDLL('./ClaRUN.dll')
MyDll = CDLL('./IC2_CommsServer.dll')
ClaRTL.AttachThreadToClarion.restype = None
ClaRTL.AttachThreadToClarion.argtypes = [c_int32]
ClaRTL.AttachThreadToClarion(1)
MyDll.SETTESTFUNC.restype = None
MyDll.SETTESTFUNC.argtypes = [CFUNCTYPE(None)]
MyDll.SETTESTFUNC (Test)
MyDll.CALLTESTFUNC.restype = None
MyDll.CALLTESTFUNC ()
_ctypes.FreeLibrary(MyDll._handle)
_ctypes.FreeLibrary(ClaRTL._handle)
print ("Done.")
SetUpDll()
Output is now:
C:\Users\Derek\AppData\Local\Programs\Python\Python38-32\python.exe Z:/ps_IC2_dll/ps_IC2_dll.py
Setting read / write callback functions... Ptr= 4 bytes
Test here
Done.
Process finished with exit code 0
I am trying to get started with Python + gRCP and so I checked out their repository as mentioned in the gRPC guide (https://grpc.io/docs/quickstart/python/).
Now I could execute the Hello World-Script (Client + Server), and so I tried to modify it. To ensure I did not missconfigure anything I just extended the Hello World-function (that use to work out before). I added the following lines:
import time
def SayHello(self, request, context):
currentTime = time.clock_gettime(time.CLOCK_REALTIME)
return helloworld_pb2.HelloReply(message='Time is, %s!' % currentTime)
Now what I inmagined it would do is to simply pass the currentTime-object back in this message I am returning upon that function is called - yet, what happens is the following error:
ERROR:grpc._server:Exception calling application: 'module' object has
no attribute 'clock_gettime' Traceback (most recent call last): File
"/home/user/.local/lib/python2.7/site-packages/grpc/_server.py", line
435, in _call_behavior
response_or_iterator = behavior(argument, context) File "greeter_server.py", line 29, in SayHello
currentTime = time.clock_gettime(time.CLOCK_REALTIME) AttributeError: 'module' object has no attribute 'clock_gettime'
I tried to Google around and I found that this might occur if you have a file named time in the same directory (so Python confuses the file in the current directory with the time-file. Yet there is no such file and he seems to find the correct time-file (since I can see the documentation when I hover the import and the function). What did I do wrong here?
The "full" Server Code (up to the serve() function):
from concurrent import futures
import logging
import time
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
currentTime = time.clock_gettime(time.CLOCK_REALTIME)
return helloworld_pb2.HelloReply(message='Time is, %s!' % currentTime)
Edit: I am using Ubuntu if that is important.
time.clock_gettime is a 3.3+ API and you are using 2.7.
I'm coding in python, using version 2.6, working with the Uber API, and when I try to import the library uber_rides.auth it throws this error:
Traceback (most recent call last):
File "C:\Inetpub\vhosts\underdevelopment.biz\httpdocs\web\webtemp3\uber\socket.py", line 4, in <module>
from uber_rides.auth import AuthorizationCodeGrant
File "C:\Inetpub\vhosts\underdevelopment.biz\httpdocs\web\webtemp3\uber\uber_rides\auth.py", line 133
query_params = [qp: query_params[qp][0] for qp in query_params]
^
SyntaxError: invalid syntax
The original code of my script is this:
print('Content-Type: text/plain')
print('')
from uber_rides.auth import AuthorizationCodeGrant
def main():
auth_flow = AuthorizationCodeGrant(
'xxxxxx-xxxxxxx',
'xxxxx-xxxxx',
'xxx-xxxxxxxxx',
'',
)
auth_url = auth_flow.get_authorization_url()
if __name__ == "__main__":
main()
It seems the error is from the library but I can't find it yet.
Yes, that's invalid Python syntax. However, it is not clear how you ended up with that file.
Someone or something altered that file. That's not the original source code as distributed by Uber, where that line uses the correct syntax for a dictionary comprehension:
query_params = {qp: query_params[qp][0] for qp in query_params}
Re-install the project, the error is not there upstream.
Note that the above syntax is only available in Python 2.7 and up. You could try to replace it with a dict() call with a generator expression, see Alternative to dict comprehension prior to Python 2.7:
query_params = dict((qp, query_params[qp][0]) for qp in query_params)
Take into account that there may be other issues with the code, upgrading to Python 2.7 is probably the better option.
I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!
I am using http://code.google.com/p/pynessus/ so that I can interact with nessus using python but I run into problems trying to connect to the server. I am not sure what I need to set pynessus too?
I try connecting to the server using the following syntax as directed by the documentation on the site but I receive the following error:
n = pynessus.NessusServer(localhost, 8834, root, password123)
Error:
root#bt:~/Desktop# ./nessus.py
Traceback (most recent call last):
File "./nessus.py", line 634, in
n = pynessus.NessusServer(localhost, 8834, root, password123)
NameError: name 'pynessus' is not defined
The problem is that you didn't import the pynessus module. To solve this problem, simply place the downloaded pynessus.py in the same folder as your Python script and add the line
import pynessus
at the top of that script. You can reference the pynessus library in your script only after that line.