Hi I am new in Python and this is an error that many people have but I could'nt be helped by any other thread. The code is straight from this tutorial .
And it posts:[ERROR] behavior.box :FMBox::createPythonModule:0 _Behavior__lastUploadedChoregrapheBehaviorbehavior_1291762048__root__headnod_1: User class evaluation failed with the error:
('expected an indented block', ('', 19, 11, 'motionProxy.angleInterpolation(names,[0.0,1.0],times,True)\n'))
Thank you in advance
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
def onLoad(self):
#put initialization code here
pass
def onUnload(self):
pass
def onInput_onStart(self):
motionProxy=ALProxy("ALMotion")
names = ['HeadYaw','HeadPitch']
times = [[0.5],[0.5]]
motionProxy.angleInterpolation(names,[0.0,0.0],times,True)
for i in range(3):
motionProxy.angleInterpolation(names,[0.0,1.0],times,True)
motionProxy.angleInterpolation(names,[0.0,-1.0],times,True)
motionProxy.angleInterpolation(names,[0.0,0.0],times,True)
self.onStopped()
def onInput_onStop(self):
self.onUnload() #it is recommended to reuse the clean-up as the box is stopped
self.onStopped() #activate the output of the box
Error says that your code is incorrectly indented.
For python you need to indent each block of code, like class body, for loop body, etc:
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
def onLoad(self):
#put initialization code here
pass
def onUnload(self):
pass
def onInput_onStart(self):
motionProxy=ALProxy("ALMotion")
names = ['HeadYaw','HeadPitch']
times = [[0.5],[0.5]]
motionProxy.angleInterpolation(names,[0.0,0.0],times,True)
for i in range(3):
motionProxy.angleInterpolation(names,[0.0,1.0],times,True)
motionProxy.angleInterpolation(names,[0.0,-1.0],times,True)
motionProxy.angleInterpolation(names,[0.0,0.0],times,True)
self.onStopped()
def onInput_onStop(self):
self.onUnload() #it is recommended to reuse the clean-up as the box is stopped
self.onStopped() #activate the output of the box
Check this chapter from Dive Into Python - Indenting Code. Also just a note that code above is not complete, it is a part of something bigger, so you anyway can't just use this code alone to do something.
Related
when I try running the code blow, I keep getting an error code that embed is already referenced even if I don't send the message ".help". Could any of you guys help me thanks.
import discord
import asyncio
from discord.ext import commands
client=discord.Client()
cliet=commands.Bot(command_prefix='.')
#client.event
async def on_ready():
print('help.py sucessfully loaded')
activity = discord.Activity(name='command watching for', type=discord.ActivityType.watching)
client = discord.Client(activity=activity)
#client.command()
async def help(ctx):
embed=discord.Embed(title="Title Here", description="Random Text Here", color=discord.Color.orange()), embed.set_footer(text="Inseart footer here"), embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url),
await ctx.channel.send(embed=embed)```
Not knowing a language is quite bad if you want to make something with the language.
Here is a minimal example of your problem:
class MyClass:
def __init__(self, arg):
self.arg = arg
def hello(self):
return "owo"
def my_func():
my_class = MyClass(1, my_class.hello()) # here, you we are trying to use `my_class` while assigning it at the same time which leads to the error.
my_func()
a more normal way such error is raised is
def my_func(x):
if x > 3:
y = 1 # if x is less than or equal to 3, y will not be assigned
return y # so what to return now? this will raise UnboundLocalVariable error
my_func(5) # works fine
my_func(100) # works fine
my_func(1) # oops, error
set_footer, set_author are bound methods of Embed object. You need an instance of it to use that. You would do these in separate lines
class MyClass:
def __init__(self, arg):
self.arg = arg
def hello(self):
return "owo"
def my_func():
my_class = MyClass(1)
my_class.hello() # now works!
my_func()
I won't be giving you the correct code for your specific problem, understand your problem, and fix it yourself.
See this line. (I added a few spaces to improve the readability)
embed = discord.Embed(title="Title Here", description="Random Text Here", color=discord.Color.orange()), embed.set_footer(text="Inseart footer here"), embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url),
What this is doing is creating a tuple, with a discord.Embed, followed by the return result of embed.set_footer, followed by the return result of embed.set_author. If we strip out the arguments, it basically comes down to this:
embed = discord.Embed(...), embed.set_footer(...), embed.set_author(...)
In basically every language, the right side of the assignment is evaluated first, and then set to the left side. This causes the method invocations to fail, because embed does not exist yet. You probably don't want embed to be a tuple anyway.
What you really want is this:
embed = discord.Embed(title="Title Here", description="Random Text Here", color=discord.Color.orange())
embed.set_footer(text="Inseart footer here")
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
This creates the embed object first, and actually sets it to an Embed, and then runs the methods that set the other things.
I think you might use the command line
client= commands.Bot(command_prefix='.', help_command=None)
So there is not a default command message and you can use your own command.
so ive got two scripts thats, where ive imported one into the other. script 1 is a class for the encryption function
class encryption():
def encryption(message):
#code here isnt relevant
def decryption(line_key):
#code isnt relevant
this code works by it self but when the other code from script two tries interacting with it it get the error :
TypeError: encryption() takes no arguments
The code for script two that interacts with script one is :
x1 = entry1.get()
label4 = tk.Label(root, text = encryption.encryption(x1), font = ('helvetica' , 10 , 'bold')
Im really not sure what im doing wrong here.
Oh you have just made a typo.
you should pass self to the definition of encryption and decryption functions in your class.
class encryption():
def encryption(self, message):
#code here isnt relevant
def decryption(self, line_key):
#code isnt relevant
I am going to attach two blocks of code, the first is the main code that is ran the second is the testClass file containing a sample class for testing purposes. To understand what's going on it's probably easiest to run the code on your own. When I call sC.cls.print2() it says that the self parameter is unfulfilled. Normally when working with classes, self (in this case) would be sC.cls and you wouldn't have to pass it as a parameter. Any advice is greatly appreciated on why this is occuring, I think it's something to do with exec's scope but even if I run this function in exec it gives the same error and I can't figure out a way around it. If you'd like any more info please just ask!
import testClass
def main():
inst = testClass.myClass()
classInfo = str(type(inst)).split()[1].split("'")[1].split('.')
print(classInfo)
class StoreClass:
def __init__(self):
pass
exec('from {} import {}'.format(classInfo[0], classInfo[1]))
sC = StoreClass()
exec('sC.cls = {}'.format(classInfo[1]))
print(sC.cls)
sC.cls.print2()
if __name__ == '__main__':
main()
class myClass:
def printSomething(self):
print('hello')
def print2(self):
print('hi')
I'm new at NAO programming and I'm having some trouble regarding the ALAudioDevice API.
My problem is the following one: I wrote a python module that should record raw data from the front microphone.
The documentation of the ALAudioDevice API says that the method "subscribe(...)" calls the function "process" automatically
and regularly with raw data from microphones as inputs. I wrote a code to execute this process (see bellow), and it runs without raising
the error flag. However, the subscribe is bypassing the function "process" and the module doesn't get any audio at all.
Has someone had the same problem?
import qi
class AudioModule(object):
def __init__(self):
super(AudioModule, self).__init__()
self.moduleName = "AudioModule"
try :
self.ALAudioDevice = ALProxy("ALAudioDevice")
except Exception, e:
self.logger.error("Error when creating proxy on ALAudioDevice:")
self.logger.error(e)
def begin_stream(self):
self.ALAudioDevice.setClientPreferences(self.moduleName, 16000, 3, 0)
self.ALAudioDevice.subscribe(self.moduleName)
def end_stream(self):
self.ALAudioDevice.unsubscribe(self.moduleName)
def processRemote( self, nbOfChannels, samplesByChannel, altimestamp, buffer ):
nbOfChannels = nbOfChannels
mylogger = qi.Logger("data")
mylogger.info("It works !" + str(nbOfChannels))
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self, False)
self.audio = AudioModule()
def onLoad(self):
self.serviceId = self.session().registerService("AudioModule", self.audio)
pass
def onUnload(self):
if self.serviceId != -1:
self.session().unregisterService(self.serviceId)
self.serviceId = -1
pass
def onInput_onStart(self):
self.audio.begin_stream()
self.onInput_onStop()
pass
def onInput_onStop(self):
self.audio.end_stream()
self.onUnload
self.onStopped()
pass
It appears you are subscribing to the audio from a Choregraphe box. I'm not sure it is supposed to work.
But in this configuration the Python code is executed from within the same process as the ALAudioDevice service. So probably you should name your callback "process" instead of "processRemote".
Otherwise, you can still do this from a separate Python script.
Here is the code sample:
class RunGui (QtGui.QMainWindow)
def __init__(self, parent=None):
...
QtCore.Qobject.connect(self.ui.actionNew, QtCore.SIGNAL("triggered()"), self.new_select)
...
def normal_output_written(self, qprocess):
self.ui.text_edit.append("caught outputReady signal") #works
self.ui.text_edit.append(str(qprocess.readAllStandardOutput())) # doesn't work
def new_select(self):
...
dialog_np = NewProjectDialog()
dialog_np.exec_()
if dialog_np.is_OK:
section = dialog_np.get_section()
project = dialog_np.get_project()
...
np = NewProject()
np.outputReady.connect(lambda: self.normal_output_written(np.qprocess))
np.errorReady.connect(lambda: self.error_output_written(np.qprocess))
np.inputNeeded.connect(lambda: self.input_from_line_edit(np.qprocess))
np.params = partial(np.create_new_project, section, project, otherargs)
np.start()
class NewProject(QtCore.QThread):
outputReady = QtCore.pyqtSignal(object)
errorReady = QtCore.pyqtSignal(object)
inputNeeded = QtCore.pyqtSignal(object)
params = None
message = ""
def __init__(self):
super(NewProject, self).__init__()
self.qprocess = QtCore.QProcess()
self.qprocess.moveToThread(self)
self._inputQueue = Queue()
def run(self):
self.params()
def create_new_project(self, section, project, otherargs):
...
# PyDev for some reason skips the breakpoints inside the thread
self.qprocess.start(command)
self.qprocess.waitForReadyRead()
self.outputReady.emit(self.qprocess) # works - I'm getting signal in RunGui.normal_output_written()
print(str(self.qprocess.readAllStandardOutput())) # prints empty line
.... # other actions inside the method requiring "command" to finish properly.
The idea is beaten to death - get the GUI to run scripts and communicate with the processes. The challenge in this particular example is that the script started in QProcess as command runs an app, that requires user input (confirmation) along the way. Therefore I have to be able to start the script, get all output and parse it, wait for the question to appear in the output and then communicate back the answer, allow it to finish and only then to proceed further with other actions inside create_new_project()
I don't know if this will fix your overall issue, but there are a few design issues I see here.
You are passing around the qprocess between threads instead of just emitting your custom signals with the results of the qprocess
You are using class-level attributes that should probably be instance attributes
Technically you don't even need the QProcess, since you are running it in your thread and actively using blocking calls. It could easily be a subprocess.Popen...but anyways, I might suggest changes like this:
class RunGui (QtGui.QMainWindow)
...
def normal_output_written(self, msg):
self.ui.text_edit.append(msg)
def new_select(self):
...
np = NewProject()
np.outputReady.connect(self.normal_output_written)
np.params = partial(np.create_new_project, section, project, otherargs)
np.start()
class NewProject(QtCore.QThread):
outputReady = QtCore.pyqtSignal(object)
errorReady = QtCore.pyqtSignal(object)
inputNeeded = QtCore.pyqtSignal(object)
def __init__(self):
super(NewProject, self).__init__()
self._inputQueue = Queue()
self.params = None
def run(self):
self.params()
def create_new_project(self, section, project, otherargs):
...
qprocess = QtCore.QProcess()
qprocess.start(command)
if not qprocess.waitForStarted():
# handle a failed command here
return
if not qprocess.waitForReadyRead():
# handle a timeout or error here
return
msg = str(self.qprocess.readAllStandardOutput())
self.outputReady.emit(msg)
Don't pass around the QProcess. Just emit the data. And create it from within the threads method so that it is automatically owned by that thread. Your outside classes should really not have any knowledge of that QProcess object. It doesn't even need to be a member attribute since its only needed during the operation.
Also make sure you are properly checking that your command both successfully started, and is running and outputting data.
Update
To clarify some problems you might be having (per the comments), I wanted to suggest that QProcess might not be the best option if you need to have interactive control with processes that expect periodic user input. It should work find for running scripts that just produce output from start to finish, though really using subprocess would be much easier. For scripts that need user input over time, your best bet may be to use pexpect. It allows you to spawn a process, and then watch for various patterns that you know will indicate the need for input:
foo.py
import time
i = raw_input("Please enter something: ")
print "Output:", i
time.sleep(.1)
print "Another line"
time.sleep(.1)
print "Done"
test.py
import pexpect
import time
child = pexpect.spawn("python foo.py")
child.setecho(False)
ret = -1
while ret < 0:
time.sleep(.05)
ret = child.expect("Please enter something: ")
child.sendline('FOO')
while True:
line = child.readline()
if not line:
break
print line.strip()
# Output: FOO
# Another line
# Done