Create class in a different file in MicroPython - nodemcu

I'm trying to use the MPU6050 module for MicroPython in NodeMCU, using uPyCraft as an editor. (https://github.com/larsks/py-mpu6050/blob/master/mpu6050.py)
I've got some troubles and I tried to simplify the code to the point I just try to call a class defined in a different file and I cannot get it to work. This is what I've done so far:
I created a new file (myFile.py) and it looks like:
import machine
class myClass(object):
def __init__(self):
print("init method called")
Then in my main.py I do:
import myFile
myclass = myFile.myClass()
I run main.py and I get this error when doing myclass = myFile.myClass() line:
'module' has no method myClass
I have no experience with MicroPython (although I'm a C# coder) so I'm pretty sure there is some detail about the syntax I'm missing. Any help?
here some tests (file name is the real one, I simplified in the question):
>>> print(open('mpuController.py').read())
import machine
class myClass(object):
def __init__(self):
print("init method called")
other:
>>> print (open('testMPU.py','r').read())
import time
import mpuController
print("starting")
mpu = mpuController.myClass()
print("finished")
and then when running:
exec(open('./testMPU.py').read(),globals())
starting
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 5, in <module>
AttributeError: 'module' object has no attribute 'myClass'

Change
import myFile.py
to
import myFile
You're importing a module (myFile), not a file. Let Python sort it out.

Related

Could not import extension ... SphinxDirective

I am trying to test the sphinx extension TODO from https://sphinx.readthedocs.io/en/master/development/tutorials/todo.html#writing-the-extension
However, this import "from docutils.parsers.rst import SphinxDirective" does not work, giving "Extension error:
Could not import extension todo (exception: No module named SphinxDirective)
"
I tried python2 and python3 , and readthedocs environment.
the code is here, https://www.sphinx-doc.org/en/master/development/tutorials/todo.html#writing-the-extension
ReadTheDocs gives this message:
Running Sphinx v1.8.5
loading translations [en]... done
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/sphinx/registry.py", line 472, in load_extension
mod = __import__(extname, None, None, ['setup'])
File "/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/checkouts/latest/docs/todo.py", line 6, in <module>
from docutils.parsers.rst import SphinxDirective
ImportError: cannot import name 'SphinxDirective' from 'docutils.parsers.rst' (/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/docutils/parsers/rst/__init__.py)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/sphinx/cmd/build.py", line 303, in build_main
args.tags, args.verbosity, args.jobs, args.keep_going)
File "/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/sphinx/application.py", line 228, in __init__
self.setup_extension(extension)
File "/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/sphinx/application.py", line 449, in setup_extension
self.registry.load_extension(self, extname)
File "/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/sphinx/registry.py", line 475, in load_extension
raise ExtensionError(__('Could not import extension %s') % extname, err)
sphinx.errors.ExtensionError: Could not import extension todo (exception: cannot import name 'SphinxDirective' from 'docutils.parsers.rst' (/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/docutils/parsers/rst/__init__.py))
Extension error:
Could not import extension todo (exception: cannot import name 'SphinxDirective' from 'docutils.parsers.rst' (/home/docs/checkouts/readthedocs.org/user_builds/demo-sphinx-extensions-for-dirac/envs/latest/lib/python3.7/site-packages/docutils/parsers/rst/__init__.py))
Well,
one has to use proper files from the tutorial, https://www.sphinx-doc.org/en/master/development/tutorials/todo.html , together with all installed packages.
This is ensured on the ReadTheDocs portal, where the extension buildup works well.
PS: Files and links are https://github.com/miroi/demo-sphinx-extensions-for-DIRAC

'DataFrame' object has no attribute 'split_frame'

Unable to Split frame using split_frame(). The dataframe is able to show() but I cannot split it. Please help.
Below is a sample of the code I have used.
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator
from __future__ import print_function
temp = spark.read.option("header","true").option("inferSchema","true").csv("hdfs://bda-ns/user/august_week2.csv")
train,test,valid = temp.split_frame(ratios=[.75, .15])
Expected: no error. Data split into test and train data frame.
Actual:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/cloudera/parcels/SPARK2-2.3.0.cloudera2-1.cdh5.13.3.p0.316101/lib/spark2/python/pyspark/sql/dataframe.py", line 1182, in __getattr__
"'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
AttributeError: 'DataFrame' object has no attribute 'split_frame'
>>> train,test,valid = temp.split_frame(ratios=[.75, .15])
Traceback (most recent call last):
File "/opt/cloudera/parcels/SPARK2-2.3.0.cloudera2-1.cdh5.13.3.p0.316101/lib/spark2/python/pyspark/context.py", line 234, in signal_handler
You could use randomsplit on your spark dataframe.
If you want to use the H2O-3 split_frame method, you would first have to convert your spark frame to an h2o frame. In which case you could use hc.as_h2o_frame(spark_df) where hc is your h2o_context (note: you would also need to create the h2o_context for this to work).

PyQt5 Signals and Slots 'QObject has no attribute' error

I have been trying to find a way to update the GUI thread from a Python thread outside of main. The PyQt5 docs on sourceforge have good instructions on how to do this. But I still can't get things to work.
Is there a good way to explain the following output from an interactive session? Shouldn't there be a way to call the emit method on these objects?
>>> from PyQt5.QtCore import QObject, pyqtSignal
>>> obj = QObject()
>>> sig = pyqtSignal()
>>> obj.emit(sig)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'QObject' object has no attribute 'emit'
and
>>> obj.sig.emit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'QObject' object has no attribute 'sig'
and
>>> obj.sig = pyqtSignal()
>>> obj.sig.emit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'PyQt5.QtCore.pyqtSignal' object has no attribute 'emit'
Following words and codes are in PyQt5 docs.
New signals should only be defined in sub-classes of QObject.They must be part of the class definition and cannot be dynamically added as class attributes after the class has been defined.
from PyQt5.QtCore import QObject, pyqtSignal
class Foo(QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = pyqtSignal()
def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)
# Emit the signal.
self.trigger.emit()
def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"

Error 1053 When Starting Window Service Written In Python

I have already looked at and tried the resolutions to this question that others have posted. One user said that to try and change my setup.py file from:
from distutils.core import setup
import py2exe
setup(console=["dev.py"])
to
from distutils.core import setup
import py2exe
setup(service=["dev.py"])
I got the following results:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "C:\Python27\Scripts\distutils-setup.py", line 5, in <module>
setup(service=["C:\Python27\Scripts\dev.py"])
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1274, in
find_needed_modules
mf.import_hook(mod)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named dev
Now, when I run py2exe with "console" in my setup script it works fine, but the service doesn't start and I get the error. When I run py2exe with "service" in my setup script py2exe doesn't run and tells me it can't find my module.
I have tried to re-install py2exe to no resolution. I have also tried to change:
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
to
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Didn't make a difference either. CAN ANYONE HELP ME PLEASE? Here is what I am working on. It monitors a server and spits back a text file every 60 seconds which I use to monitor my servers at any given minute. Any help you guys and gals can give would be great.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import wmi
import _winreg
from time import sleep
import os
class SrvMonSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "SrvMonSvc"
_svc_display_name_ = "Server Monitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
host = wmi.WMI(namespace="root/default").StdRegProv
try:
result, api = host.GetStringValue(
hDefKey = _winreg.HKEY_LOCAL_MACHINE,
sSubKeyName = "SOFTWARE\Server Monitor",
sValueName = "API")
if api == None:
raise Exception
else:
pass
except:
exit()
while 1 == 1:
with open("C:/test.txt", "wb") as b:
computer = wmi.WMI(computer="exsan100")
for disk in computer.Win32_LogicalDisk (DriveType=3):
name = disk.caption
size = round(float(disk.Size)/1073741824, 2)
free = round(float(disk.FreeSpace)/1073741824, 2)
used = round(float(size), 2) - round(float(free), 2)
for mem in computer.Win32_OperatingSystem():
a_mem = (int(mem.FreePhysicalMemory)/1024)
for me in computer.Win32_ComputerSystem():
t_mem = (int(me.TotalPhysicalMemory)/1048576)
u_mem = t_mem - a_mem
for cpu in computer.Win32_Processor():
load = cpu.LoadPercentage
print >>b, api
print >>b, name
print >>b, size
print >>b, used
print >>b, t_mem
print >>b, u_mem
print >>b, load
b.close()
date_list = []
stamp = time.strftime("%c",time.localtime(time.time()))
date_list.append(stamp)
name = re.sub(r"[^\w\s]", "",date_list[0])
os.rename("C:/test.txt", ("C:/%s.txt" % name))
try:
sleep(60.00)
except:
exit()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SrvMonSvc)
Have you progressed from your original problem. I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete.
Running pythonservice.exe with -debug from the command prompt was not a problem because it used correct PATH environment variable, but if your service is installed as a System service it's worth checking out if the System Path variable has all the paths for the required DLLs (MSVC, Python, System32). For me it was missing the python DLLs path, after that it worked again.

GAE + Python2.7 + webapp2 + AJAX

Are there any tutorials or code examples related to AJAX implementation for GAE + Python2.7 + webapp2.
I have tried to follow instructions below:
http://code.google.com/appengine/articles/rpc.html
but I receive the following error:
Traceback (most recent call last):
File "E:\dev\workspace\test\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "E:\dev\workspace\test\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "E:\dev\workspace\test\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "E:\dev\workspace\test\webapp2.py", line 1101, in __call__
handler = self.handler(request, response)
TypeError: __init__() takes exactly 1 argument (3 given)
There is another similar discussion here:
Google App Engine Python Protorpc Error: __call__() takes exactly 1 argument (3 given)
heres is my code from Specialscope's example:
main.py
from BaseHandler import BaseHandler
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import logging
from google.appengine.api import files
from google.appengine.api import images
import json
import webapp2
class FileuploadHandler(BaseHandler):
def get(self):
blobstore.create_upload_url('/static')
context={}
self.render_response("uploader.html",**context)
class FileDownloadHandler(blobstore_handlers.BlobstoreUploadHandler,BaseHandler):
def post(self):
upload_files=self.request.POST
#image=upload_files['file']
logging.error(upload_files)
keys=upload_files.keys()
imageurls=[]
for key in keys:
if key.find("uploadimage")!=-1:
image=upload_files[key]
file_name=files.blobstore.create(mime_type='image/jpg')
with files.open(file_name,'a') as f:
f.write(image.value)
files.finalize(file_name)
blob_key=files.blobstore.get_blob_key(file_name)
imageurls.append(images.get_serving_url(blob_key))
context={}
context['imagelinks']=imageurls
self.response.write(json.dumps(context))
app = webapp2.WSGIApplication([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
], debug = True)
BaseHandler.py
import webapp2
import os
from webapp2_extras import jinja2
from google.appengine.ext import db
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
The stack trace suggests that you have a url mapping in your WSGIApplication that has a group in it, but there's no handler with the corresponding arguments.
If you have
(r'/foo/(\s+)/(\s+)', FooHandler),
then you need
class FooHandler(webapp2.RequestHandler):
def get(self, arg1, arg2):
...
The doc you're using pre-dates Python 2.7 support by several years. Were I in your position, I'd be tempted to get the app working first on Python 2.5, then port to 2.7.
The problem is here:
import webapp2
app = webapp2.WSGIApplication([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
], debug = True)
You can't use webapp2.WSGIApplication to construct your application, it doesn't understand protorpc. Instead, do this:
from protorpc.wsgi import service
app = service.service_mappings([
('/upload', FileuploadHandler),
('/download', FileDownloadHandler),
])

Resources