Cmd module not cooperating with *args - python

I am trying to develop my Binance client with the Cmd module, however when I try to call a function from another file, it gives me an error.
This is for a Binance client i am writing.
main.py
def do_order(self, *args):
"""Places an order.\n
Arguments in order:\n
Buy or Sell option.\n
Market or Limit option.\n
The crypto symbol.\n
The quantity of the order.\n
The price of the order.\n"""
market.Market.xch(*args[0], *args[1], *args[2], *args[3], *args[4])
market.py
class Market():
#l = 0
#m = 0
#b = 0
#s = 0
def xch(self, xtype1, xtype2, xsymbol, xquantity, xprice ):
print("Formulating the order...")
#Time to sort the parameters
#xtype1...
Errors
[verl#verlpc Interface]$ python main.py
Loading Accounts...
CRYPTOANAYLISIS: PREDICTOR
> order 0 0 0 0 0
Traceback (most recent call last):
File "main.py", line 99, in <module>
m.initAccounts()
File "main.py", line 92, in initAccounts
prompt.cmdloop('CRYPTOANAYLISIS: PREDICTOR')
File "/usr/lib/python3.7/cmd.py", line 138, in cmdloop
stop = self.onecmd(line)
File "/usr/lib/python3.7/cmd.py", line 217, in onecmd
return func(arg)
File "main.py", line 50, in do_order
market.Market.xch(*args[0], *args[1], *args[2], *args[3], *args[4])
IndexError: tuple index out of range

First you have to create instance of this class
m = market.Market()
And then you have use single *args
m.xch(*args)
or many arguments but without *
m.xch(args[0], args[1], args[2], args[3], args[4])
Working example
class Market():
def xch(self, xtype1, xtype2, xsymbol, xquantity, xprice ):
print("Formulating the order...", xtype1, xtype2, xsymbol, xquantity, xprice)
args = [1,2,3,4,5]
m = Market()
m.xch(*args)
EDIT: you have to use do_order(...)
with * in definiton and when you run it
def do_order(*args):
m = Market()
m.xch(*args)
args = [1,2,3,4,5]
do_order(*args)
or without * in both places
def do_order(args):
m = Market()
m.xch(*args)
args = [1,2,3,4,5]
do_order(args)

Related

Stuck on Python "KeyError: <exception str() failed>" in BFS code of a water jug scenario

Intended Function of code: Takes a user input for the volume of 3 jars(1-9) and output the volumes with one of the jars containing the target length. jars can be Emptied/Filled a jar, or poured from one jar to another until one is empty or full.
With the code I have, i'm stuck on a key exception error .
Target length is 4 for this case
Code:
`
class Graph:
class GraphNode:
def __init__(self, jar1 = 0, jar2 = 0, jar3 = 0, color = "white", pi = None):
self.jar1 = jar1
self.jar2 = jar2
self.jar3 = jar3
self.color = color
self.pi = pi
def __repr__(self):
return str(self)
def __init__(self, jl1 = 0, jl2 = 0, jl3 = 0, target = 0):
self.jl1 = jl1
self.jl2 = jl2
self.jl3 = jl3
self.target = target
self.V = {}
for x in range(jl1 + 1):
for y in range(jl2 + 1):
for z in range(jl3 + 1):
node = Graph.GraphNode(x, y, z, "white", None)
self.V[node] = None
def isFound(self, a: GraphNode) -> bool:
if self.target in [a.jar1, a.jar2, a.jar3]:
return True
return False
pass
def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:
if self.V[a]==b:
return True
return False
pass
def BFS(self) -> [] :
start = Graph.GraphNode(0, 0, 0, "white")
queue=[]
queue.append(start)
while len(queue)>0:
u=queue.pop(0)
for v in self.V:
if self.isAdjacent(u,v):
if v.color =="white":
v.color == "gray"
v.pi=u
if self.isFound(v):
output=[]
while v.pi is not None:
output.insert(0,v)
v=v.pi
return output
else:
queue.append(v)
u.color="black"
return []
#######################################################
j1 = input("Size of first jar: ")
j2 = input("Size of second jar: ")
j3 = input("Size of third jar: ")
t = input("Size of target: ")
jar1 = int(j1)
jar2 = int(j2)
jar3 = int(j3)
target = int(t)
graph1 = Graph(jar1, jar2, jar3, target)
output = graph1.BFS()
print(output)
`
**Error: **
line 37, in isAdjacent
if self.V[a]==b:
KeyError: <exception str() failed>
Strange but when I first ran this in the IPython interpreter I got a different exception:
... :35, in Graph.isAdjacent(self, a, b)
34 def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:
---> 35 if self.V[a]==b:
36 return True
37 return False
<class 'str'>: (<class 'RecursionError'>, RecursionError('maximum recursion depth exceeded while getting the str of an object'))
When I run it as a script or in the normal interpreter I do get the same one you had:
... line 35, in isAdjacent
if self.V[a]==b:
KeyError: <exception str() failed>
I'm not sure what this means so I ran the debugger and got this:
File "/Users/.../stackoverflow/bfs1.py", line 1, in <module>
class Graph:
File "/Users/.../stackoverflow/bfs1.py", line 47, in BFS
if self.isAdjacent(u,v):
File "/Users/.../stackoverflow/bfs1.py", line 35, in isAdjacent
if self.V[a]==b:
KeyError: <unprintable KeyError object>
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /Users/.../stackoverflow/bfs1.py(35)isAdjacent()
-> if self.V[a]==b:
(Pdb) type(a)
<class '__main__.Graph.GraphNode'>
(Pdb) str(a)
*** RecursionError: maximum recursion depth exceeded while calling a Python object
So it does seem like a maximum recursion error. (The error message you originally got is not very helpful). But the words <unprintable KeyError object> are a clue. It looks like it was not able to display the KeyError exception...
The culprit is this line in your class definition:
def __repr__(self):
return str(self)
What were you trying to do here?
The __repr__ function is called when the class is asked to produce a string representation of itself. But yours calls the string function on the instance of the class so it will call itself! So I think you actually generated a second exception while the debugger was trying to display the first!!!.
I replaced these lines with
def __repr__(self):
return f"GraphNode({self.jar1}, {self.jar2}, {self.jar3}, {self.color}, {self.pi})"
and I don't get the exception now:
Size of first jar: 1
Size of second jar: 3
Size of third jar: 6
Size of target: 4
Traceback (most recent call last):
File "/Users/.../stackoverflow/bfs1.py", line 77, in <module>
output = graph1.BFS()
File "/Users/.../stackoverflow/bfs1.py", line 45, in BFS
if self.isAdjacent(u,v):
File "/Users/.../stackoverflow/bfs1.py", line 33, in isAdjacent
if self.V[a]==b:
KeyError: GraphNode(0, 0, 0, white, None)
This exception is easier to interpret. Now it's over to you to figure out why this GraphNode was not found in the keys of self.V!

Once my functions are nested and reference eachother, my tuples return NoneType errors, why?

I wrote functions to call and replace tuples from a dictionary. The functions all work independently. When I run them individually the tuple values return integers as planned. When run in sequence or nested with other functions, the tuples return NoneType error. When I run type on my called tuple it returns integer. I'm confused and wanted to solve this issue before I convert to a class structure to tidy up.
My current workflow is: takes in an integer determined from previous code (volume)> conditionally chooses a divisor> rounds down the value> matches the value in a dictionary> returns the value from the dictionary> new tuple created> tuple in dictionary is replaced
TypeError Traceback (most recent call last)
<ipython-input-23-1f1ae48bdda3> in <module>
----> 1 asp_master(275,dict_tuberack1,vol_tuberack1,tuberack1,'A1')
2 height_a1= get_height(dict_tuberack1,tuberack1,'A1')
3 asp_a(275,height_a1,tuberack1['A1'])
4 disp_master(275,dict_tuberack1,vol_tuberack1,tuberack1,'A2')
5 height_a2= get_height(dict_tuberack1,tuberack1,'A2')
<ipython-input-10-ba8bc2194a15> in asp_master(volume, dict_vol, dict_labware, labware, well)
1 def asp_master(volume,dict_vol,dict_labware,labware,well):
----> 2 if low_vol_check(volume,dict_labware,labware,well)==True:
3 new_vol=volume_sub(volume,dict_labware,labware,well)
4 tup_update_sub(new_vol,dict_vol,dict_labware,labware,well)
5 print(dict_labware[labware[well]])
<ipython-input-16-a23165d51020> in low_vol_check(volume, dict_labware, labware, well)
10
11 def low_vol_check(volume,dict_labware,labware,well):
---> 12 x=get_volume(dict_labware,labware,well)
13 y=volume
14 if x-y < 0:
<ipython-input-16-a23165d51020> in get_volume(dict_labware, labware, well)
1 def get_volume(dict_labware,labware,well):
2 tup = dict_labware.get(labware[well])
----> 3 (tup_v,tup_h)=tup
4 volume=tup_v
5 return tup_v
TypeError: cannot unpack non-iterable NoneType object
Robot Code:
from opentrons import protocol_api
from opentrons.simulate import get_protocol_api
from math import floor,ceil
from datetime import datetime
import opentrons
protocol = get_protocol_api('2.8')
tuberack1 = protocol.load_labware('opentrons_15_tuberack_nest_15ml_conical','2', 'tuberack1')
tuberack2 = protocol.load_labware('opentrons_24_tuberack_nest_1.5ml_snapcap','3','tuberack2')
tiprack= protocol.load_labware('opentrons_96_tiprack_300ul','4')
p300 = protocol.load_instrument('p300_single', 'left', tip_racks=[tiprack])
p300.home
Code:
dict_tuberack1={tuberack1['A1']:(14000,104), tuberack1['A2']:(14000,104), tuberack1['A3']:(14000,104),}
vol_tuberack1= {14000: 104, 13500: 101, 13000: 98, 12500: 94,
12000: 91, 11500: 88, 11000: 85, 10500: 81,
10000: 78, 9500: 75, 9000: 72, 8500: 68,
8000: 65, 7500: 62, 7000: 59, 6500: 55,
6000: 52, 5500: 49,}
def get_volume(dict_labware,labware,well):
tup = dict_labware.get(labware[well])
(tup_v,tup_h)=tup
volume=tup_v
return tup_v
def low_vol_check(volume,dict_labware,labware,well):
x=get_volume(dict_labware,labware,well)
y=volume
if x-y < 0:
return False
else:
return True
def tup_update_sub(volume,dict_vol,dict_labware,labware,well):
tup = dict_labware.get(labware[well])
adj_list=list(tup)
adj_list[0]=volume
divisor=1
if volume >=1000:
divisor=1000
vol_even=round_down(volume, divisor)
elif 100 <= volume <1000: #this was the issue and was fixed.
divisor=100
vol_even=round_down(volume,divisor)
else:
divisor=10
vol_even=round_down(volume,divisor)
new_height=dict_vol.get(vol_even)
adj_list[1]=new_height
new_tup=tuple(adj_list)
dict_labware[labware[well]] = new_tup
def asp_master(volume,dict_vol,dict_labware,labware,well):
if low_vol_check(volume,dict_labware,labware,well)==True:
new_vol=volume_sub(volume,dict_labware,labware,well)
tup_update_sub(new_vol,dict_vol,dict_labware,labware,well)
print(dict_labware[labware[well]])
else:
print('Cannot aspirate')
#robot commands below
def asp_a (volume,height,source):
p300.pick_up_tip()
p300.aspirate(volume, source.bottom(z=height))
def disp_a (volume,height,destination):
p300.dispense(volume,destination.bottom(z=height+8))
p300.blowout(height+8)
#code that generated error message below
asp_master(275,dict_tuberack1,vol_tuberack1,tuberack1,'A1')
height_a1= get_height(dict_tuberack1,tuberack1,'A1')
asp_a(275,height_a1,tuberack1['A1'])

Object has no attribute but also get global name not defined

I am trying my darnest to pull a variable from a text file to do some math in an trading bot algorithim.
This is my code. I have shortened it to get to the issue:
from botlog import BotLog
from botindicators import BotIndicators
from bottrade import BotTrade
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
self.trades = [] #20 trades at 0.021 = .042
self.currentPrice = "" #after a day, add the BTC to 0.042 and adjust simultaneous trades
self.currentClose = "" #53 coins for 2500 simul trades per coin pair
self.numSimulTrades = 100 #looks like dash ends at 2500 trades eth ends at about 1000 trades total for all four would be about 208 coins
self.indicators = BotIndicators()
mid=0
with open('test.txt', 'r') as myfile:
mid=myfile.read().replace('\n', '')
self.output.log(mid)
mid=int(mid)
def tick(self,candlestick):
self.currentPrice = float(candlestick.priceAverage)
self.prices.append(self.currentPrice)
#self.currentClose = float(candlestick['close'])
#self.closes.append(self.currentClose)
self.output.log("Price: "+str(candlestick.priceAverage)+"\tMoving Average: "+str(self.indicators.movingAverage(self.prices,5)))
self.evaluatePositions()
self.updateOpenTrades()
self.showPositions()
def evaluatePositions(self):
openTrades = []
for trade in self.trades:
if (trade.status == "OPEN"):
openTrades.append(trade)
if (len(openTrades) < self.numSimulTrades):
if ((self.currentPrice) < self.indicators.movingAverage(self.prices,15)):
self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001))
for trade in openTrades:
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
trade.close(self.currentPrice)
def updateOpenTrades(self):
for trade in self.trades:
if (trade.status == "OPEN"):
trade.tick(self.currentPrice)
def showPositions(self):
for trade in self.trades:
trade.showTrade()
With "self.mid" I get the error: 'Bot1' object has no attribute 'mid'
a if I remove the "self" I get: NameError: global name 'mid' is not defined
What am I doing wrong? I'm losing my mind!
Traceback was requested: This is the No Attribute:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
self.currentPrice= float(self.currentPrice+self.mid)
AttributeError: 'BotStrategy' object has no attribute 'mid'
And this is "mid" not defined:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
NameError: global name 'mid' is not defined
bottrade.py code:
from botlog import BotLog
import botstrategy
def main(argv):
currentMovingAverage = 0;
tradePlaced = False
typeOfTrade = False
dataDate = ""
orderNumber = ""
dataPoints = []
localMax = []
currentResistance = 0.018
mid = int(mid)
class BotTrade(object):
def __init__(self,currentPrice,stopLoss=0):
self.output = BotLog()
prices = []
self.status = "OPEN"
self.entryPrice = currentPrice
self.exitPrice = ""
self.output.log("Trade opened")
if (stopLoss):
self.stopLoss = currentPrice - stopLoss
def close(self,currentPrice):
self.mid = int(mid)
if currentPrice > (self.entryPrice + self.mid): #DASH likes about 0.000937, XRP about 0.000001, ETH likes 0.000855 XMR likes 0.000396
#use ETH to start with, with less than 4 trades. you get about 1.7 BTC in a week - 4 trades # 0.021=0.084 BTC. Daily is 0.24
self.status = "CLOSED"
self.exitPrice = currentPrice
self.output.log("Trade closed")
def tick(self, currentPrice):
if (self.stopLoss):
if (currentPrice < self.stopLoss):
self.close(currentPrice)
def showTrade(self):
tradeStatus = "Entry Price: "+str(self.entryPrice)+" Status: "+str(self.status)+" Exit Price: "+str(self.exitPrice)
if (self.status == "CLOSED"):
tradeStatus = tradeStatus + " Profit:! "
if (self.exitPrice > self.entryPrice):
tradeStatus = tradeStatus + " \033[92m"
else:
tradeStatus = tradeStatus + " \033[91m"
tradeStatus = tradeStatus+str(abs((self.exitPrice) - (self.entryPrice)))+" \033[0m"
self.output.log(tradeStatus)
Traceback from bottrade.py
user#user1:~/Desktop/bot/part3$ python backtest.py
Price: 1131.71486314 Moving Average: None
Price: 1103.73203402 Moving Average: 1117.72344858
Trade opened
Entry Price: 1103.73203402 Status: OPEN Exit Price:
Price: 1108.36463027 Moving Average: 1114.60384248
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 29, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
trade.close(self.currentPrice)
File "/home/user/Desktop/bot/part3/bottrade.py", line 30, in close
self.mid = int(mid)
NameError: global name 'mid' is not defined
Full display now. Any help would be appreciated.
The run-time system is correct. In the mid case, there is no variable mid defined in evaluatePositions. Similarly, there is no object attribute mid for instances of BotStrategy. Look at the difference in your initialization:
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
...
mid=int(mid)
mid is a local variable of init, not an attribute. Perhaps you need
self.mid = int(mid)
and the use self.mid when you reference that value.
Does that work for you?

AttributeError: 'bool' object has no attribute 'items'

I'm a beginner in python. I'm currently try to deal with use the IK to move the robot arm. When I try to run my program the arm was able to move to the my setted starting position but when it's going to next step it shows me this error:AttributeError: 'bool' object has no attribute 'items'
This is my program:
class Pick_Place (object):
#def __init__(self,limb,hover_distance = 0.15):
def __init__(self,limb):
self._limb = baxter_interface.Limb(limb)
self._gripper = baxter_interface.Gripper(limb)
self._gripper.calibrate(limb)
#self.gripper_open()
#self._verbose = verbose
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService"
self._iksvc = rospy.ServiceProxy(ns,SolvePositionIK)
rospy.wait_for_service(ns, 5.0)
def move_to_start (self,start_angles = None):
print ("moving.....")
if not start_angles:
print ("it is 0")
start_angles = dict(zip(self._joint_names, [0]*7))
self._guarded_move_to_joint_position(start_angles)
self.gripper_open()
rospy.sleep(1.0)
print ("moved!!!")
#########################IK_Server################################################
def ik_request (self,pose):
hdr = Header(stamp=rospy.Time.now(),frame_id='base')
ikreq = SolvePositionIKRequest()
ikreq.pose_stamp.append(PoseStamped(header=hdr, pose=pose))
try:
resp = self._iksvc (ikreq)
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
limb_joints = {}
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
return limb_joints
###################################################################################
def _guarded_move_to_joint_position(self,joint_angles):
print ("joint position.....")
self._limb.move_to_joint_positions(joint_angles)
def gripper_open (self):
self._gripper.open()
rospy.sleep(1.0)
def gripper_close (self):
self._gripper.close()
rospy.sleep(1.0)
#################################Individual_Motion####################################
def _approach (self, pose):
print ("\nApproaching.....")
approach = copy.deepcopy(pose)
approach.position.z = approach.position.z #+ self._hover_distance
joint_angles = self.ik_request(approach)
self._guarded_move_to_joint_position(joint_angles)
print ("\nApproached.....")
def _retract (self):
print ("\nRetracting.....")
current_pose = self._limb.endpoint_pose()
ik_pose = Pose()
ik_pose.position.x = current_pose['position'].x
ik_pose.position.y = current_pose['position'].y
ik_pose.position.z = current_pose['position'].z #+ self._hover_distance
ik_pose.orientation.x = current_pose['orientation'].x
ik_pose.orientation.y = current_pose['orientation'].y
ik_pose.orientation.z = current_pose['orientation'].z
ik_pose.orientation.w = current_pose['orientation'].w
joint_angles = self.ik_request(ik_pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nRetracted......")
def _servo_to_pose (self, pose):
print ("\nPosing.....")
joint_angles = self.ik_request(pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nPosed.....")
##########################Motion_of_pick_and_place#####################################
def pick (self,pose):
print ("\nPicking_1.....")
# open the gripper
self.gripper_open()
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# close gripper
self.gripper_close()
# retract to clear object
self._retract()
print ("\nPicked")
def place (self,pose):
print ("\nPlacing_1.....")
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# open the gripper
self.gripper_open()
# retract to clear object
self._retract()
print ("\nPlaced")
###########################Main_Program############################################
def main():
print ("Initializing....")
rospy.init_node("ylj_ik_traTest")
print("Getting the robot state.....")
rs= baxter_interface.RobotEnable()
print ("Enabling....")
rs.enable()
limb = 'left'
#hover_distance = 0.15
starting_joint_angles = {'left_s0': -0.50,
'left_s1': -1.30,
'left_e0': -0.60,
'left_e1': 1.30,
'left_w0': 0.20,
'left_w1': 1.60,
'left_w2': -0.30}
#pnp = Pick_Place(limb,hover_distance)
pnp = Pick_Place(limb)
overhead_orientation = Quaternion(
x=-0.0249590815779,
y=0.999649402929,
z=0.00737916180073,
w=0.00486450832011)
ball_poses = list()
#1st ball point
ball_poses.append(Pose(
position = Point(x=0.7, y=0.15, z=-0.1),
orientation = overhead_orientation))
#2nd ball point
ball_poses.append(Pose(
position = Point(x=0.75, y=0.0, z=-0.1),
orientation = overhead_orientation))
pnp.move_to_start(starting_joint_angles)
idx = 0
while not rospy.is_shutdown():
print ("\nPicking.....")
pnp.pick(ball_poses[idx])
print ("\nPlacing.....")
idx = (idx+1) % len(ball_poses)#?????
pnp.place(ball_poses[idx])
return 0
if __name__ == '__main__':
sys.exit(main())
And this is the error shows me:
Initializing....
Getting the robot state.....
Enabling....
[INFO] [WallTime: 1466477391.621678] Robot Enabled
moving.....
joint position.....
moved!!!
Picking.....
Picking_1.....
Approaching.....
joint position.....
Traceback (most recent call last):
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 197, in <module>
sys.exit(main())
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 188, in main
pnp.pick(ball_poses[idx])
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 122, in pick
self._approach(pose)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 88, in _approach
self._guarded_move_to_joint_position(joint_angles)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 72, in _guarded_move_to_joint_position
self._limb.move_to_joint_positions(joint_angles)
File "/home/baxter/ros_ws/src/baxter_interface/src/baxter_interface/limb.py", line 368, in move_to_joint_positions
diffs = [genf(j, a) for j, a in positions.items() if
AttributeError: 'bool' object has no attribute 'items'
Does anyone had met this kind of error before? Please help me, thank you.
The error tells you that booleans (either True or False) don't have an attribute "items".
When you call
self._limb.move_to_joint_positions(joint_angles) you are passing the argument "joint_angles" which becomes "positions" in the function
move_to_joint_positions().
Looking into the source code of the library you're using, it tells you what it wants positions to be:
#type positions: dict({str:float})
In short, it wants joint_angles to be a dictionary mapping strings to floats and you passed a boolean. Let's look into how you got joint_angles:
joint_angles = self.ik_request(ik_pose)
In the body of your method, you return False every time:
def ik_request (self,pose):
...
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
Returning a boolean is clearly not what you want to do, and it is the cause of this error.
You're trying to access the elements of a boolean value, which is not allowed. In your example, positions is a true/false value and not what you're expecting it to be. There's some section of the code where positions is being assigned to a boolean. You should walk through your code and look for any line that contains positions = something.

Weird bug in python project

I'm working on a big project in Python, and I've run into a bizarre error I can't explain. In one of my classes, I have a private method being called during instantiation:
def _convertIndex(self, dimInd, dimName):
'''Private function that converts numbers to numbers and non-integers using
the subclass\'s convertIndex.'''
print dimInd, ' is dimInd'
try:
return int(dimName)
except:
if dimName == '*':
return 0
else:
print self.param.sets, ' is self.param.sets'
print type(self.param.sets), ' is the type of self.param.sets'
print self.param.sets[dimInd], ' is the param at dimind'
return self.param.sets[dimInd].value(dimName)
What it's printing out:
0 is dimInd
[<coremcs.SymbolicSet.SymbolicSet object at 0x10618ad90>] is self.param.sets
<type 'list'> is the type of self.param.sets
<SymbolicSet BAZ=['baz1', 'baz2', 'baz3', 'baz4']> is the param at dimind
======================================================================
ERROR: testParameterSet (GtapTest.TestGtapParameter)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/myuser/Documents/workspace/ilucmc/gtapmcs/test/GtapTest.py", line 116, in testParameterSet
pset = ParameterSet(prmFile, dstFile, GtapParameter)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/ParameterSet.py", line 103, in __init__
self.distroDict, corrDefs = AbsBaseDistro.readFile(distFile, self.paramDict)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 359, in readFile
distro = cls.parseDistro(param, target, distroType, args)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 301, in parseDistro
return cls(param, target, distro, dim_names, argDict)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 150, in __init__
self.dim_indxs = list(starmap(self._convertIndex, enumerate(dim_names))) # convert to numeric values and save in dim_indxs
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 194, in _convertIndex
print self.param.sets[dimInd], ' is the param at dimind'
IndexError: list index out of range
Obviously this isn't the code for the whole class, but it represents something that I don't understand. The error is coming when I index into self.param.sets. Apparently, dimInd is out of range. the problem is, dimInd is 0, and self.param.sets is a list of length 1 (as shown from the print statements), so why can't I index into it?
EDIT: For what it's worth, the __init__ method looks like this:
'''
Stores a definitions of a distribution to be applied to a header variable.
See the file setup/gtap/DistroDoc.txt for the details.
'''
def __init__(self, param, target, distType, dim_names, argDict):
self.name = param.name
self.dim_names = dim_names
self.dim_indxs = []
self.target = target.lower() if target else None
self.distType = distType.lower() if distType else None
self.rv = None
self.argDict = {}
self.modifier = defaultdict(lambda: None)
self.param = param
# Separate args into modifiers and distribution arguments
for k, v in argDict.iteritems():
if k[0] == '_': # modifiers start with underscore
self.modifier[k] = v
else:
self.argDict[k] = v # distribution arguments do not have underscore
if self.target == 'index':
print dim_names
self.dim_indxs = list(starmap(self._convertIndex, enumerate(dim_names))) # convert to numeric values and save in dim_indxs
if distType == 'discrete':
entries = self.modifier['_entries']
if not entries:
raise DistributionSpecError("Not enough arguments given to discrete distribution.")
modDict = {k[1:]: float(v) for k, v in self.modifier.iteritems() if k[1:] in getOptionalArgs(DiscreteDist.__init__)}
self.rv = DiscreteDist(entries, **modDict)
return
sig = DistroGen.signature(distType, self.argDict.keys())
gen = DistroGen.generator(sig)
if gen is None:
raise DistributionSpecError("Unknown distribution signature %s" % str(sig))
self.rv = gen.makeRV(self.argDict) # generate a frozen RV with the specified arguments
self.isFactor = gen.isFactor

Categories

Resources