python class attribute not updating when updated in a function - python

I have a stopwatch of sorts going in the background using threading, and while it's updating the global variable, it doesn't change the output of my class attribute.
This is what I have:
import time
from threading import Thread
s = 0
m = 0
h = 0
stopped = False
def stopwatch():
global s
global m
global h
global stopped
while stopped == False:
s = s + 1
if s >= 60:
s = 0
m += 1
if m >= 60:
m = 0
h += 1
time.sleep(1)
class foo:
name = 'shirb'
time = str(h) + 'h' + str(m) + 'm' + str(s) +'s'
Thread(target = stopwatch).start()
input('press enter to stop the stopwatch')
stopped = True
print('Name: ' + foo.name + '\nTime: ' + foo.time)
Lets say I wait for one minute and 34 seconds.
The output should be:
press enter to stop the stopwatch
Name: shirb
Time: 0h1m34s
But this is what it actually puts out:
press enter to stop the stopwatch
Name: shirb
Time: 0h0m0s
I have no idea what is causing it to not update. When I try to print the variable itself with "print(s)" i get the correct amount of seconds, so there is something wrong with the class attribute that I don't know how to fix.

Class variables are initialized at module load time, so foo.time is set when h, m, and s, are zero. If you make it a class method, however, you will get the right result:
class foo:
name = 'shirb'
#classmethod
def cls_time(cls):
return str(h) + 'h' + str(m) + 'm' + str(s) +'s'
Thread(target = stopwatch).start()
input('press enter to stop the stopwatch')
stopped = True
print('Name: ' + foo.name + '\nTime: ' + foo.cls_time())

You could perhaps use just the one class:
import time
from threading import Thread
class stopwatch:
def __init__(self):
self.s = 0
self.m = 0
self.h = 0
self.stopped = False
self.name = "shirb"
def begin(self):
while self.stopped is False:
self.s += 1
if self.s >= 60:
self.s = 0
self.m += 1
if self.m >= 60:
self.m = 0
self.h += 1
time.sleep(1)
def get_time(self):
return str(self.h) + "h" + str(self.m) + "m" + str(self.s) + "s"
s = stopwatch()
Thread(target=s.begin).start()
input("press enter to stop the stopwatch")
s.stopped = True
print("Name: " + s.name + "\nTime: " + s.get_time())
This solves the issue.

Related

Function call not working proparly (python)

For input 1 to self.trying, the set_jump() method doesn't work. the program dosent execute the while loop in it
Code:
jump = []
z = []
class jumps:
def __init__(self, numberOfJumps, trying):
self.numberOfJumps = numberOfJumps
self.trying = int(trying)
def setJumps(self):
if self.trying == 1:
# print("hello")
self.set_jump()
if self.trying == 2:
self.get_jump()
return ""
def set_jump(self):
counterSetJump = 0
while counterSetJump < int(self.numberOfJumps):
print("what was the distance the athlete jumped at jump number" + str(counterSetJump + 1))
z.append(float(input()))
counterSetJump += 1
return ""
def get_jump(self):
counterGetJumps = 0
while counterGetJumps < int(self.numberOfJumps):
print(z[counterGetJumps])
print("this is the jump for the " + str(counterGetJumps) + " time")
counterGetJumps += 1
return ""
class athlete:
def __init__(self, name, yearsPro):
self.name = name
self.yearsPro = yearsPro
def information(self):
print("the athletes name is " + self.name)
print("he as been active for " + str(self.yearsPro))
return ""
a = []
b = []
i = 0
know = int(input("how many athletes you know the information for"))
while i < know:
a.append(0)
b.append(0)
i = i + 1
j = 0
while j < know:
a[j] = athlete(input("what is the athletes name?"), input("how many years as the athlete been active"))
b[j] = jumps(input("how many jumps did the athlete jumped?"),
input("input 1 for settig and 2 for getting the jumps")) # not getting called?
b[j].setJumps()
j = j + 1
infoFor = int(input("who do you want the info for"))
print(a[int(infoFor) - 1].information())
print(b[int(infoFor) - 1].get_jump())
Check the code out
jump = []
z = []
class jumps:
def __init__(self, numberOfJumps, trying):
self.numberOfJumps = numberOfJumps
self.trying = int(trying)
print("trying = "+str(self.trying))
def setJumps(self) :
if self.trying == 1:
#print("hello")
self.set_jump()
if self.trying == 2:
self.get_jump()
print("Yes I have chnaged trying to = :"+str(self.trying))
return ""
def set_jump(self):
print("set_jump finally called")
i = 0
while(i < int(self.numberOfJumps)):
print("what was the distance the athlete jumped at jump number" + str(i))
z.append(int(input()))
i = i + 1
def get_jump(self):
i = 0
while(i < int(self.numberOfJumps)):
return z[i]
i = i + 1
class athlete:
def __init__(self, name, yearsPro):
self.name = name
self.yearsPro = yearsPro
def information(self):
print("the athletes name is " + self.name)
print("he as been active for " + str(self.yearsPro))
return ""
a = []
b = []
i = 0
know = int(input("how many athletes you know the information for"))
while(i < know):
a.append(0)
b.append(0)
i = i + 1
j = 0
while(j <know):
a[j] = athlete(input("what is the athletes name?"), input("how many years as the athlete been active"))
b[j] = jumps(input("how many jumps did the athlete jumped?"),
input("input 1 for settig and 2 for getting the jumps")) #not getting called?
b[j].setJumps()
k=j
for k in b:
k.setJumps()
#j=j+1
j = j + 1
infoFor = int(input("who do you want the info for"))
print(a[int(infoFor) - 1].information())
print(b[int(infoFor) - 1].setJumps())

loop instance method with list elements

I am trying to write a program (API testing) to loop through instance methods in a class. One of the methods "get_one_sale_license" has a variable "self.sale_sgid_in_test" I need to assign this variable each element in the list "sale_list_final" .The variable is used in the instance method as well as the main function. I put a for loop outside the class and it works fine with the output( this is modified part of a single file from the application using framework).
However, I want to remove the loop wrapping the class and try in a more pythonic way.
import json
from datetime import *
from N import NSession
from N import NArgParser
from i_data_provider import iDataProvider
sale_list = open("sales.txt").readlines()
sale_list_final = [s.rstrip() for s in sale_list]
tests_list = open("tests.txt").readlines()
tests_list_final = [t.rstrip() for t in tests_list]
cnt=0
cnt2=0
cnt3=0
cnt6=0
cnt11=0
for i in sale_list_final:
class iDeployChecks:
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
# self.sale_sgid_list = []
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
def get_all_saleable_sales(self):
global cnt2
if cnt2 == 0:
self.i_session.get_sale_seller_info()
self.logger.info('SUCCESS..... Get all sales api\n')
cnt2 += 1
def get_all_sale_dashboard(self):
global cnt6
if cnt6 == 0:
self.i_session.get_All_sale()
self.logger.info('SUCCESS..... Get all sales on dashboard api\n')
cnt6 += 1
def get_current_user_sale_dashboard(self):
global cnt11
if cnt11 == 0:
self.i_session.get_current_user_sale()
self.logger.info('SUCCESS..... Get current sales on dashboard api\n')
cnt11 += 1
def get_one_sale_license(self):
self.logger.info('Getting sale details from:')
self.sale_sgid_list1 = [item.get('salesgid') for item in self.i_session.get_sale_seller_info()]
#self.sale_sgid_list =[item.get('salesgid') for item in self.i_session.get_sale_seller_info() if item.get('salesgid') == i]
print " for sale " + str(i)
self.sale_sgid_in_test = ''.join(i)
self.logger.info('\n')
self.logger.info('Get License for sale with sale sgid {}'.format(self.sale_sgid_in_test))
self.i_session.get_sale_license(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... Get license api\n')
def get_weekly_stats_count(self):
global cnt
if cnt == 0:
self.i_session.get_weekly_statistics()
self.logger.info('SUCCESS..... Weekly statistics api\n')
cnt += 1
def get_sconfig_value_count(self):
self.i_session.get_sconfig_value(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... sconfig api\n')
def main(self):
start = datetime.utcnow()
# check if the method in the list is present in the class, if yes run it.
for j in tests_list_final:
k = "self." + j + "()"
l= [x.strip() for x in j.split(',')]
m= "self."+l[0]+"(self,year)"
n= "self."+l[0]+"(self,year,month)"
if k == str("self.get_all_saleable_sales()"):
if cnt2 == 0:
self.logger.info('Get All sales')
self.get_all_saleable_sales()
self.logger.info('checking if sale with GSID ' + i + ' exists')
if i not in str(self.i_session.get_sale_seller_info()):
print "the sale with GSID " + i + " does not exist !!"
end1 = datetime.utcnow()
self.logger.info('i health check completed in {} seconds.'.format((end1 - start).seconds))
return
else:
print "sale exists !!"
continue
elif k == str("self.get_one_sale_license()"):
self.get_one_sale_license()
continue
elif k == str("self.get_sale_node_status_value()"):
try:
self.logger.info('Get sale node status for sale sgid {}'.format(self.sale_sgid_in_test))
self.get_sale_node_status_value()
except Exception as e: print e
else:
global cnt3
if (cnt3==0):
print '\n'
print " The testcase " +k + "test does not exist,please recheck test name !!"
print '\n'
cnt3 +=1
end = datetime.utcnow()
self.logger.info('IBDL health check completed in {} seconds.'.format((end - start).seconds))
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
iDeployChecks(args.badge, args.environment).main()
Remove the loop and include in the init
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
self.sale_sgid_list = [i for i in sale_list_final]
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
Then loop for the same list element while calling the main
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
for i in sale_sgid_list:
iDeployChecks(args.badge, args.environment,i).main()

Gdax Candle Stick using Python

Anyone here with an idea of how to loop a constantly moving variable within a timeframe of 60 seconds to check it's highest, medium, lowest and average of the three?
Then creating more of a json objects of the past minutes
Tried using timer for custom threading and seems that it is not working for me
Below is my code. Kindly assist.
import sys, getopt
import time
from threading import Timer
import main.botlog as botlog
from main.settings import auth_client,product
class BotCandlestick(object):
def __init__(self, period=60, open=None, close=None, high=None, low=None, priceAverage=None):
self.current = None
self.open = open
self.close = close
self.high = high
self.low = low
self.startTime = time.time()
self.period = period
BotLog = botlog.BotLog
self.output = BotLog()
self.priceAverage = priceAverage
def tick(self, price):
# while True:
self.current = float(price)
if (self.open is None):
self.open = self.current
print(self.open)
if ((self.high is None) or (self.current > self.high)):
self.high = self.current
print(self.high)
if ((self.low is None) or (self.current < self.low)):
self.low = self.current
print(self.low)
if (time.time() >= (self.startTime + self.period)):
self.close = self.current
self.priceAverage = (self.high + self.low + self.close) / float(3)
print(self.priceAverage)
self.output.log(
"Open: " + str(self.open) + " Close: " + str(self.close) + " High: " + str(self.high) + " Low: " + str(
self.low) + " Current: " + str(self.current))
def isClosed(self):
if (self.close is not None):
return True
else:
return False
def main():
price = auth_client.get_product_ticker(product)
prices = float(price.get('price'))
price = BotCandlestick()
d = price.tick(prices)
t = Timer(10.0, d)
t.start()
if __name__ == '__main__':
main()
I did figure out a universal way to go about this problem. Kindly find the code below. It is more of a universal code to find value change within x time.
import gdax
import time
public = gdax.PublicClient()
while True:
endtime = time.time() + 60
x = []
while time.time() < endtime:
ticker = public.get_product_ticker('BTC-USD')
ticker = ticker['price']
ticker = float(ticker)
x.append(ticker)
change = ((x[0]-x[-1])/x[-1])
print(ticker)
time.sleep(1)
print("Open: {} High: {} Low: {} Close: {} Change: {}%".format(x[0], max(x), min(x), x[-1], change*100))
time.sleep(0)

I got stuck on Python error TypeError: unhashable type: 'slice'

from informedSearch import *
from search import *
class EightPuzzleProblem(InformedProblemState):
"""
Inherited from the InformedProblemState class. To solve
the eight puzzle problem.
"""
def __init__(self, myList, list = {}, operator = None):
self.myList = list
self.operator = operator
def __str__(self):
## Method returns a string representation of the state.
result = ""
if self.operator != None:
result += "Operator: " + self.operator + ""
result += " " + ' '.join(self.myList[0:3]) + "\n"
result += " " + ' '.join(self.myList[3:6]) + "\n"
result += " " + ' '.join(self.myList[6:9]) + "\n"
return result
def illegal(self):
## Tests whether the state is illegal.
if self.myList < 0 or self.myList > 9: return 1
return 0
def equals(self, state):
## Method to determine whether the state instance
## and the given state are equal.
return ' '.join(self.myList) == ' '.join(state.myList)
## The five methods below perform the tree traversing
def move(self, value):
nList = self.myList[:] # make copy of the current state
position = nList.index('P') # P acts as the key
val = nList.pop(position + value)
nList.insert(position + value, 'P')
nList.pop(position)
nList.insert(position, val)
return nList
def moveleft(self):
n = self.move(-1)
return EightPuzzleProblem(n, "moveleft")
def moveright(self):
n = self.move(1)
return EightPuzzleProblem(n, "moveright")
def moveup(self):
n = self.move(-3)
return EightPuzzleProblem(n, "moveup")
def movedown(self):
n = self.move(+3)
return EightPuzzleProblem(n, "movedown")
def operatorNames(self):
return ["moveleft", "moveright", "moveup", "movedown"]
def enqueue(self):
q = []
if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6):
q.append(self.moveleft())
if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8):
q.append(self.moveright())
if self.myList.index('P') >= 3:
q.append(self.moveup())
if self.myList.index('P') >= 5:
q.append(self.movedown())
def applyOperators(self):
return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()]
def heuristic():
counter = 0
for i in range(len(self.myList)):
if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'):
## Position of current:
current = goal.myList.index(self.myList[i])
if current < 3: goalRow = 0
elif current < 6: goalRow = 1
else: goalRow = 2
if i < 3: initRow = 0
elif i < 6: initRow = 1
else: startRow = 2
initColumn = i % 3
goalColumn = current % 3
counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow))
return counter
#Uncomment to test the starting states:
init = ['1','3','P','8','2','4','7','6','5'] #A
#init = ['1','3','4','8','6','2','P','7','5'] #B
#init = ['P','1','3','4','2','5','8','7','6'] #C
#init = ['7','1','2','8','P','3','6','5','4'] #D
#init = ['8','1','2','7','P','4','6','5','3'] #E
#init = ['2','6','3','4','P','5','1','8','7'] #F
#init = ['7','3','4','6','1','5','8','P','2'] #G
#init = ['7','4','5','6','P','3','8','1','2'] #H
goal = ['1','2','3','8','P','4','7','6','5'] #goal state
InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal))
I run it and it shows error
line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n"
TypeError: unhashable type: 'slice'
Any Ideas?
You're setting the "list" to a dictionary as a default value: list = {} in:
def __init__(self, myList, list = {}, operator = None):
and then assigning it to myList with:
self.myList = list
A dictionary cannot be sliced like a list. So when you try to slice it:
self.myList[0:3]
it fails.

Is this python code thread-safe?

I am trying to make my chunk of code non-thread-safe, in order to toy with some exceptions that I want to add on later.
This is my python code:
from time import sleep
from decimal import *
from threading import Lock
import random
def inc_gen(c):
"""
Increment generator
"""
while True:
#getting sleep period
timing_rand = random.randrange(0,1000)
print "INC: Sleeping for " + str(Decimal(timing_rand)/Decimal(1000))
sleep(Decimal(timing_rand)/Decimal(1000))
c.inc()
yield c
def dec_gen(c):
"""
decrement generator
"""
while True:
#getting sleep period
timing_rand = random.randrange(0,1000)
print "DEC: Sleeping for " + str(Decimal(timing_rand)/Decimal(1000))
sleep(Decimal(timing_rand)/Decimal(1000))
c.dec()
yield c
class something():
"""
We use an obj instead of an atomic variable c, we can have "threads"
simulating shared resources, instead of a single variable, to avoid
atomic instructions. (which is thread-safe in python thanks to GIL)
"""
def __init__(self):
self.c = 0
def inc(self):
self.c += 1
def dec(self):
self.c -= 1
def value(self):
return self.c
def main():
"""
main() function
"""
obj = something()
counters = [inc_gen(obj),dec_gen(obj)]
#we only want inc_gen 10 times, and dec_gen 10 times.
inc = 0 #number of times inc_gen is added
dec = 0 #number of times dec_gen is added
while True:
#choosing the next counter
if inc < 10 and dec < 10:
counter_rand = random.randrange(0,2)
if counter_rand == 0:
inc += 1
else: dec += 1
elif inc < 10 and dec == 10:
inc += 1
counter_rand = 0
elif dec < 10 and inc == 10:
dec += 1
counter_rand = 1
else: break
counters[counter_rand].next()
#print for testing
print "Final value of c: " + str(obj.value())
if __name__ == "__main__":
main()
What I want it to do is to have the code possibly result in a final value which is not 0.
Is it thread-safe? If not, how can I make it such that it is not thread-safe?
You have a Read-Modify-Write operation basically. If you want to ensure things go haywire, the best is to intruduce delay between the read and the write.
def inc(self):
v = self.c
time.sleep(random.random()) # Should probably limit it to a few hundred ms
self.c = v + 1
def dec(self):
v = self.c
time.sleep(random.random()) # Should probably limit it to a few hundred ms
self.c = v - 1

Categories

Resources