Python RPC Time module function not found - python

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.

Related

Using Python COM objects from Excel VBA

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.

Python can't import WMI under special circumstance

I've created a standalone exe Windows service written in Python and built with pyInstaller. When I try to import wmi, an exception is thrown.
What's really baffling is that I can do it without a problem if running the code in a foreground exe, or a foreground python script, or a python script running as a background service via pythonservice.exe!
Why does it fail under this special circumstance of running as a service exe?
import wmi
Produces this error for me:
com_error: (-2147221020, 'Invalid syntax', None, None)
Here's the traceback:
Traceback (most recent call last):
File "<string>", line 43, in onRequest
File "C:\XXX\XXX\XXX.pyz", line 98, in XXX
File "C:\XXX\XXX\XXX.pyz", line 31, in XXX
File "C:\XXX\XXX\XXX.pyz", line 24, in XXX
File "C:\XXX\XXX\XXX.pyz", line 34, in XXX
File "C:\Program Files (x86)\PyInstaller-2.1\PyInstaller\loader\pyi_importers.py", line 270, in load_module
File "C:\XXX\XXX\out00-PYZ.pyz\wmi", line 157, in <module>
File "C:\XXX\XXX\out00-PYZ.pyz\win32com.client", line 72, in GetObject
File "C:\XXX\XXX\out00-PYZ.pyz\win32com.client", line 87, in Moniker
wmi.py line 157 has a global call to GetObject:
obj = GetObject ("winmgmts:")
win32com\client__init.py__ contains GetObject(), which ends up calling Moniker():
def GetObject(Pathname = None, Class = None, clsctx = None):
"""
Mimic VB's GetObject() function.
ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will
connect to an already running instance of the COM object.
ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax)
will return a ready to use Python wrapping of the required COM object.
Note: You must specifiy one or the other of these arguments. I know
this isn't pretty, but it is what VB does. Blech. If you don't
I'll throw ValueError at you. :)
This will most likely throw pythoncom.com_error if anything fails.
"""
if clsctx is None:
clsctx = pythoncom.CLSCTX_ALL
if (Pathname is None and Class is None) or \
(Pathname is not None and Class is not None):
raise ValueError("You must specify a value for Pathname or Class, but not both.")
if Class is not None:
return GetActiveObject(Class, clsctx)
else:
return Moniker(Pathname, clsctx)
The first line in Moniker(), i.e. MkParseDisplayName() is where the exception is encountered:
def Moniker(Pathname, clsctx = pythoncom.CLSCTX_ALL):
"""
Python friendly version of GetObject's moniker functionality.
"""
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
Note: I tried using
pythoncom.CoInitialize()
which apparently solves this import problem within a thread, but that didn't work...
I also face the same issue and I figure out this issue finally,
import pythoncom and CoInitialize pythoncom.CoInitialize (). They import wmi
import pythoncom
pythoncom.CoInitialize ()
import wmi
I tried solving this countless ways. In the end, I threw in the towel and had to just find a different means of achieving the same goals I had with wmi.
Apparently that invalid syntax error is thrown when trying to create an object with an invalid "moniker name", which can simply mean the service, application, etc. doesn't exist on the system. Under this circumstance "winmgmts" just can't be found at all it seems! And yes, I tried numerous variations on that moniker with additional specs, and I tried running the service under a different user account, etc.
Honestly I didn't dig in order to understand why this occurs.
Anyway, the below imports solved my problem - which was occurring only when ran from a Flask instance:
import os
import pythoncom
pythoncom.CoInitialize()
from win32com.client import GetObject
import wmi
The error "com_error: (-2147221020, 'Invalid syntax', None, None)" is exactly what popped up in my case so I came here after a long time of searching the web and voila:
Under this circumstance "winmgmts" just can't be found at all it
seems!
This was the correct hint for because i had just a typo , used "winmgmt:" without trailing 's'. So invalid sythax refers to the first methods parameter, not the python code itself. o_0 Unfortunately I can't find any reference which objects we can get with win32com.client.GetObject()... So if anybody has a hint to which params are "allowed" / should work, please port it here. :-)
kind regards
ChrisPHL

AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'

I'm currently trying to build a Script that interacts with Google's API's, but I keep getting an Attribute error:
Traceback (most recent call last):
File "service_catalog_automation.py", line 18, in <module>
feed = client.GetDocumentListFeed()
AttributeError: 'DocsClient' object has no attribute 'GetDocumentListFeed'
This is the code I'm trying to use
import gdata.gauth
import gdata.docs.client
import sys
def sys_print(text):
sys.stdout.write(str(text))
sys.stdout.flush()
CONSUMER_KEY = 'domain.com'
CONSUMER_SECRET = 'abcde1234'
requestor_id = 'myuser#domain.com'
client = gdata.docs.client.DocsClient(source='my-script-v1')
client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
CONSUMER_KEY, CONSUMER_SECRET, requestor_id)
# Retrieve user's list of Google Docs
feed = client.GetDocumentListFeed()
for entry in feed.entry:
sys_print(entry.title.text)
sys_print('\n')
I've pulled client.getDocumentListFeed() portion of code from their sample code here and have even tried a bare minimum approach using their sample code under the 2LeggedOAuth section here. (I also have tried GetDocList() from that example with the same error)
I have downloaded Google's gdata-python-client to a linux vm's home directory and installed it by running python setup.py install and ran the test python all_tests.py with no errors.
Any help would be greatly apperciated
In the first example, they're assigning their client object as the return of gdata.docs.service.DocsService().
The second example also returns the client object as a DocsService type:
client = gdata.docs.service.DocsService(source='yourCompany-YourAppName-v1')
This would seem to imply that gd_client is of type DocsService, not DocsClient

Is it possible to serialize tasklet code (not just exec state) using SPickle without doing a RPC?

Trying to use stackless python (2.7.2) with SPickle to send a test method over celery for execution on a different machine. I would like the test method (code) to be included with the pickle and not forced to exist on the executing machines python path.
Been referencing following presentation:
https://ep2012.europython.eu/conference/talks/advanced-pickling-with-stackless-python-and-spickle
Trying to use the technique shown in the checkpointing slide 11. The RPC example doesn't seem right given that we are using celery:
Client code:
from stackless import run, schedule, tasklet
from sPickle import SPickleTools
def test_method():
print "hello from test method"
tasks = []
test_tasklet = tasklet(test_method)()
tasks.append(test_tasklet)
pt = SPickleTools(serializeableModules=['__test_method__'])
pickled_task = pt.dumps(tasks)
Server code:
pt = sPickle.SPickleTools()
unpickledTasks = pt.loads(pickled_task)
Results in:
[2012-03-09 14:24:59,104: ERROR/MainProcess] Task
celery_tasks.test_exec_method[8f462bd6-7952-4aa1-9adc-d84ee4a51ea6] raised exception:
AttributeError("'module'
object has no attribute 'test_method'",)
Traceback (most recent call last):
File "c:\Python27\lib\site-packages\celery\execute\trace.py", line 153, in trace_task
R = retval = task(*args, **kwargs)
File "c:\Python27\celery_tasks.py", line 16, in test_exec_method
unpickledTasks = pt.loads(pickled_task)
File "c:\Python27\lib\site-packages\sPickle\_sPickle.py", line 946, in loads
return unpickler.load()
AttributeError: 'module' object has no attribute 'test_method'
Any suggestions on what I am doing incorrect or if this is even possible?
Alternative suggestions for doing dynamic module loading in a celeryd would also be good (as an alternative for using sPickle). I have experimented with doing:
py_mod = imp.load_source(module_name,'some script path')
sys.modules.setdefault(module_name,py_mod)
but the dynamically loaded module does not seem to persist through different calls to celeryd, i.e. different remote calls.
You must define test_method within its own module. Currently sPickle detects whether test_method is defined in a module that can be imported. An alternative way is to set the __module__ attribute of the function to None.
def test_method():
pass
test_method.__module__ = None

PermanentTaskFailure: 'module' object has no attribute 'Migrate'

I'm using Nick Johnson's Bulk Update library on google appengine (http://blog.notdot.net/2010/03/Announcing-a-robust-datastore-bulk-update-utility-for-App-Engine). It works wonderfully for other tasks, but for some reason with the following code:
from google.appengine.ext import db
from myapp.main.models import Story, Comment
import bulkupdate
class Migrate(bulkupdate.BulkUpdater):
DELETE_COMPLETED_JOBS_DELAY = 0
DELETE_FAILED_JOBS = False
PUT_BATCH_SIZE = 1
DELETE_BATCH_SIZE = 1
MAX_EXECUTION_TIME = 10
def get_query(self):
return Story.all().filter("hidden", False).filter("visible", True)
def handle_entity(self, entity):
comments = entity.comment_set
for comment in comments:
s = Story()
s.parent_story = comment.story
s.user = comment.user
s.text = comment.text
s.submitted = comment.submitted
self.put(s)
job = Migrate()
job.start()
I get the following error in my logs:
Permanent failure attempting to execute task
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 258, in post
run(self.request.body)
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 122, in run
raise PermanentTaskFailure(e)
PermanentTaskFailure: 'module' object has no attribute 'Migrate'
It seems quite bizarre to me. Clearly that class is right above the job, they're in the same file and clearly the job.start is being called. Why can't it see my Migrate class?
EDIT: I added this update job in a newer version of the code, which isn't the default. I invoke the job with the correct URL (http://version.myapp.appspot.com/migrate). Is it possible this is related to the fact that it isn't the 'default' version served by App Engine?
It seems likely that your declaration of the 'Migrate' class is in the handler script (Eg, the one directly invoked by app.yaml). A limitation of deferred is that you can't use it to call functions defined in the handler module.
Incidentally, my bulk update library is deprecated in favor of App Engine's mapreduce support; you should probably use that instead.

Categories

Resources