I have a python file called myGlobal.py, in this file I declared count as a global variable.
import datetime
import time
import os
count = 0
failCount = 0
def counterstart:
global count
count +=1
I am calling this counter in another file. So every time I call a function, I want the counter to increase by 1. That file is scripts.py
import os
from selenium import webdriver
import datetime
import time
from myGlobal import *
def main():
fnfirst()
fnsecond()
fnthird()
def fnfirst():
global count
print count
def fnsecond():
global count
print count
def fnthird():
global count
print count
main()
But whenever I run script.py, the count is shown as 0 only.
Why is this happening?
import myGlobal
print myGlobal.count # 0
myGlobal.count += 1
def foo():
myGlobal.count += 1
foo()
print myGlobal.count # 2
So here is a solution based on the Python's decorators. It will count the number of call on specific functions :
# File script.py
import myGlobal
def count_call(func):
def _wrapper(*args, **kwargs):
myGlobal.count += 1
func(*args, **kwargs)
return _wrapper
#count_call
def fnfirst():
pass # do something
#count_call
def fnsecond():
pass # do something
def main():
print myGlobal.count # 0
fnfirst()
print myGlobal.count # 1
fnsecond()
print myGlobal.count # 2
fnfirst()
print myGlobal.count # 3
if __name__ == "__main__":
main()
Related
I'm trying to make thread counter but I'm stuck. I've got the code below:
import threading
def Hello():
global t
print("Hello!")
t = threading.Timer(1, Hello)
t.start()
Hello()
How can I make the loop stop say after 5 'Hellos'?
Not sure what you're trying to accomplish but this code will work
import threading
count = 0
def hello():
global count
print("Hello!")
count += 1
if count < 5:
t = threading.Timer(1, function=hello,)
t.start()
hello()
I have the following decorator running fine using a parameter
from functools import wraps
def sumproduct(cnt):
def dec(f):
#wraps(f)
def wrap(*args):
print('inside wrapper')
_sum = 0
for i in range(cnt):
_sum = _sum + sum([i * a for a in args])
f(_sum)
return wrap
return dec
cnt = 3
#sumproduct(cnt)
def myfunc(num):
print(num)
if __name__ == "__main__":
myfunc(10)
The output is 30 which is 0*10 + 1*10+ 2*10
However, I would like to import this module somewhere else, for example into a test module. I would like to do something like the following so that cnt is not defined in global scope:
from functools import wraps
def sumproduct(cnt):
def dec(f):
#wraps(f)
def wrap(*args):
print('inside wrapper')
_sum = 0
for i in range(cnt):
_sum = _sum + sum([i * a for a in args])
f(_sum)
return wrap
return dec
#sumproduct(cnt)
def myfunc(num):
print(num)
if __name__ == "__main__":
cnt = 3
myfunc(10)
How can I define cnt so that
cnt is always 3 when code is executed?
and cnt is not imported when module is imported?
Note: This is just a sample representation of the code. Suppose that cnt is database connection which connects to production database. I would like to use a different database connection for tests, hence I don't want to import production database connection into test module.
You could use #sumproduct(lambda: cnt). That way the execution is delayed.
For example:
from functools import wraps
def sumproduct(cnt):
def dec(f):
#wraps(f)
def wrap(*args):
print('inside wrapper')
_sum = 0
for i in range(cnt()): # <---- Note the ()
_sum = _sum + sum([i * a for a in args])
f(_sum)
return wrap
return dec
#sumproduct(lambda: cnt) # <--- put lambda: here
def myfunc(num):
print(num)
if __name__ == "__main__":
cnt = 3
myfunc(10)
Prints:
inside wrapper
30
I want to call the printFunction method every __ seconds, but I want to stop the scheduling after a certain number of calls. Say for example, print every 5 seconds 10 times. Pulling those frequency and run time values in from another file.
Running in PyCharm.
import schedule
import time
class example:
# basic function to print
def printFunction(self):
print("Hello world")
def repeated(self):
# reads in two values from another file
systemFrequency = float(freqSettings.systemFrequency)
systemRunTime = int(freqSettings.systemRunTime)
global count
count = 0
while (count < systemRunTime):
self.printFunction
self.increaseCount
def increaseCount(self):
global count
count += 1
The function run by the scheduler need to return CancelJob to stop being scheduled.
Here is how i've implemented it :
import schedule
def my_function():
print("hello world")
def wrapper():
wrapper.counter +=1
my_function()
if wrapper.counter == 10:
return schedule.CancelJob
wrapper.counter = 0
schedule.every(1).seconds.do(wrapper)
while True:
schedule.run_pending()
print(schedule)
It displays 10 "hello world"
I am using this code to call a function doSomething every 3 seconds. but I want that when numeroPeticiones== 3, stop doing it. I have looked for many examples, but none works. In my case, my function continues to be executed eternally, even though the condition of numeroPeticiones== 3 is fulfilled. how can I solve that?
import threading
from threading import Timer
numeroPeticiones=0
def doSomething():
global numeroPeticiones
numeroPeticiones=numeroPeticiones+1
print ("hello, world",numeroPeticiones)
if numeroPeticiones == 3:
print("cancel")
t.cancel()
def set_interval(func, sec):
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
You can do the following, if num is equal to the 3, it wont start the timer
from threading import Timer
num = 0
def hello():
global num
num += 1
print("hello, world")
if (num < 3):
Timer(3, hello).start()
Timer(3, hello).start()
My questions are interlaced within my code:
#!/usr/bin/python
import threading
import logging, logging.handlers
import hpclib
import json
import time
from datetime import datetime
from features import *
import sys
if len(sys.argv) != 3:
print "Please provide the correct inputs"
print "Usage: rest_test.py <controllerip> <counter>"
sys.exit()
controller = sys.argv[1]
counter = int(sys.argv[2])
class FuncThread(threading.Thread):
def __init__(self, target, *args):
self._target = target
self._args = args
threading.Thread.__init__(self)
def run(self):
self._target(*self._args)
def datapath_thread(ipaddress, testlogfile,count):
#initialize logging system
testlogger = logging.getLogger("testlogger")
testlogger.setLevel(logging.DEBUG)
file = open(testlogfile,'w')
file.close()
# This handler writes everything to a file.
h1 = logging.FileHandler(testlogfile)
f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
h1.setFormatter(f)
h1.setLevel(logging.DEBUG)
testlogger.addHandler(h1)
mylib = hpclib.hpclib(ipaddress)
success_count = 0
failure_count = 0
for i in range(count):
t1=datetime.now()
try:
(code, val) = datapaths.listDatapaths(mylib)
I want to pass this function datapaths.listDatapaths(mylib) as a argument from a thread below, something like (code,val)=functionname
if code == 200:
success_count +=1
else:
testlogger.debug("Return Code other than 200 received with code = %d, value = %s"%(code,val))
failure_count +=1
except:
failure_count += 1
testlogger.debug ("Unexpected error: %s"%sys.exc_info()[0])
continue
t2=datetime.now()
diff=t2-t1
testlogger.debug('RETURN code: %d. Time taken in sec = %s,Iteration = %d, Success = %d, Failure = %d'%(code,diff.seconds,i+1,success_count,failure_count))
time.sleep(1)
testlogger.removeHandler(h1)
# Passing ipadress of controller and log file name
t1 = FuncThread(datapath_thread, controller, "datapaths.log",counter)
Here I would like to pass function name as one of the argument,something like t1 = FuncThread(datapath_thread, controller, datapaths.listDatapaths(mylib),"datapaths.log",counter)
t1.start()
t1.join()
I have many functions to call like this,so want a easy way to call all the functions from one single function using many threads
Firstly, FuncThread is not very useful - FuncThread(func, *args) can be spelt Thread(target=lambda: func(*args)) or Thread(target=func, args=args).
You're pretty close - instead of passing in the result of calling the function, pass in the function itself
def datapath_thread(ipaddress, test_func, testlogfile, count):
# ...
for i in range(count):
# ...
try:
(code, val) = test_func(mylib)
#...
thread = Thread(target=datapath_thread, args=(
controller,
datapaths.listDatapaths,
"datapaths.log",
counter
))