How to make like global variable which refreshes itself from db [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have program which is running forever (while True) and that is ok, but I need inside to use number which represents number of users in table (it isn't necessary to be precise so I wnat to avoid COUNT(*) query to database whenever I need that number, but problem is when it has large error between real number and that number). I thought to make that my number refreshes every day. How to make like global variable which refreshes itself with but not to running forever (when it refreshes it doesn't use any CPU time) ?

Use a class property and only hit the server again if some time has elapsed.
from datetime import datetime, timedelta
import random
class MyThing(object):
def __init__(self, refresh_interval=60*60*24):
self.refresh_interval = refresh_interval
self._n_users = None
self._last_refresh = datetime.now() - timedelta(0, refresh_interval)
# setup db connection stuff
#property
def n_users(self):
if (datetime.now() - self._last_refresh).total_seconds() > self.refresh_interval:
self._n_users = self.fetch_from_db()
self._last_refresh = datetime.now()
return self._n_users
def fetch_from_db(self):
# TODO
return random.randint(0, 100)
t = MyThing(refresh_interval=3)
print t.n_users

Use a thread and make it sleep between attempts to update the variable.
#!python2
import threading
import time
global_count = 0
def UpdateUserCount():
while True:
# code to update user count
# global_count = ...
time.sleep(86400); # one day
if __name__ == '__main__':
thr = threading.Thread( target=UpdateUserCount )
thr.start()
# Do other stuff.

Related

simple mqtt script in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
My code is working well as expected but i would like to improve it. When a loop enter in a big time sleep like 100s how can i force it to change imediatly. if i miss input and put 400s and not 4s i would have to restart the program it's anoying. Here you can see the code
I tried many things like making other variable etc but i'm new and quiet lost.
`import paho.mqtt.client
import time
import threading
monClientMqtt = paho.mqtt.client.Client()
monClientMqtt.connect("localhost",1883)
monClientMqtt.loop_start()
monClientMqtt.subscribe("option")
monClientMqtt.subscribe("periodeX")
monClientMqtt.subscribe("mesureX")
monClientMqtt.subscribe("periodeY")
monClientMqtt.subscribe("mesureY")
monClientMqtt.subscribe("valeurX")
monClientMqtt.subscribe("valeurY")
periodeX =1
mesureX=0
x=0
y=0
periodeY=1
mesureY=0
def CallBack (client, userdata,message) :
global x,periodeX,mesureX,y, periodeY,mesureY
print(message.topic)
print(message.payload)
if message.topic == "option" :
if message.payload.decode() == "restartX" :
x=0
if message.payload.decode()=="restartY":
y=0
if message.topic =="mesureX":
try:
mesureX=float(message.payload.decode())
except ValueError:
print("0 ou 1")
if message.topic =="periodeX" :
try:
periodeX=float(message.payload.decode())
except ValueError :
print("Veuillez entrer un nombre")
if message.topic =="mesureY":
try:
mesureY=float(message.payload.decode())
except ValueError:
print("0 ou 1")
if message.topic =="periodeY" :
try:
periodeY=float(message.payload.decode())
except ValueError :
print("Veuillez entrer un nombre")
def prendremesureX():
while True:
if mesureX==0:
global x,periodeX
x+=1
monClientMqtt.publish("valeurX",x)
time.sleep(periodeX)
def prendremesureY():
while True :
if mesureY==0:
global y,periodeY
y+=1
monClientMqtt.publish("valeurY",y)
time.sleep(periodeY)
threadX=threading.Thread(target=prendremesureX)
threadY=threading.Thread(target=prendremesureY)
monClientMqtt.on_message=CallBack
threadX.start()
threadY.start()
Please see the other comments directing you on how to properly ask questions/how to use stack overflow.
Question issues aside, if I am understanding your question correctly, you are asking; "How can I adjust the delay of my checks, in case there is an emergent need?"
The problem with your current implementation, is that you are using time.sleep(), which is functionally suspending any processing until the time frame expires. This won't work, as you have discovered, since no changes can be made mid-sleep.
What you are looking to do, is to create a task scheduler. You would want to assign a date or time to a specific task, and have a task handler that would do processing of each task, depending on the particular time.
Subsequently, if something needs to be urgently processed, you would update the scheduled time of the task, to be processed as needed.

Python - Undo script if script fails [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Sometimes when I run a function in my python script and if the function gives me an output which is not desired, I need to undo this step and then try running the function again with different parameters. Is there a way that I can have the script undo what it has done if my function gives me a wrong output.For only one set of parameters, the desired output is acheived.
PS: By running the function means making permanent changes.
Example:
def function():
for i in range(parameters):
value = perform_operation(parameters[i]) #makes permanent changes
if value != some_value:
undo(perform_operation())
You need to create another function than cleans what was done in the main function for example (delete newly created files, remove installed packages, etc ...) and use it.
def main_func():
proc = subprocess.Popen('touch test test2')
return proc.returncode
def clean_main_func():
subprocess.Popen('rm test test2')
def __name__ == '__main__':
result = main_func()
if main_func() != 0 :
clean_main_func()
or you can raise an error then catch it:
def main_func():
proc = subprocess.Popen('touch test test2')
if proc.returncode !=0 :
raise Error
def clean_main_func():
subprocess.Popen('rm test test2')
def __name__ == '__main__':
try:
result = main_func()
except Error:
clean_main_func()
It's juste an example , and hope it answer your question.

function start to run in the first second of the minute [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want a function start to run in the first second of the minute but i can't do it
this is my code
import datetime
now = datetime.datetime.now()
while not (now.second == "01"):now = datetime.datetime.now()
Your code doesn't work because you're comparing a number (now.second) to a string "01". In Python numbers and their string representations are not equal (unlike some other programming languages), so this will never work.
Try comparing with 1 (or maybe 0 if you really want the top of the minute). And maybe instead of busy-looping (which will use all of one core of your CPU while waiting), you should perhaps instead use time.sleep to wait until the start of the next minute.
import datetime
import time
now = datetime.datetime.now()
sec = now.second
if sec != 0:
time.sleep(60-sec)
# it should be (close to) the top of the minute here!
There's always some unpredictability when dealing with time on a computer, since your program might be delayed from running by the OS at any moment (more likely if your CPU is very busy). I'd not worry about it too much though, likely it's good enough to be very close to the right time.
import time
while True:
if time.strftime("%S") == "01":
#Run Your Code
time.sleep(59)
That would pound your system like crazy, give it a little room to breathe:
import time
while True:
current_seconds = time.gmtime().tm_sec
if current_seconds == 1:
print("The first second of a minute...")
time.sleep(0.9) # wait at least 900ms before checking again
You can further streamline it by calculating how much time to wait before you start checking again - if you're interested only in the first second you can safely sleep until the end of the minute.

Doing something after for loop finishes in same function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is this possible? I'm doing an bukkit plugin now (in Python, yes :D), and I'm forced to do this within one function, so I can't separate it and call it later... For example, if I have loop that loops through players on server and adds everyone except one player, I want it to finish, and then teleport i.e. "Player1" to random player. At the moment, it teleports "Player1" to random player every time because of for loop... I'll give you just little of code, since It looks messy in preview due to many things that are not involved in problem and could be confusable to you... Here it is:
listica = []
for p1 in org.bukkit.Bukkit.getWorld(nextvalue).getPlayers():
if p1.getName() not in listica:
try:
listica.remove(event.getPlayer().getName())
randomtarget = choice(listica)
randomtargetreal = org.bukkit.Bukkit.getPlayer(randomtarget)
event.getPlayer().teleport(randomtargetreal)
event.getPlayer().sendMessage("%sYou teleported to: %s%s"% (bukkit.ChatColor.GREEN, bukkit.ChatColor.DARK_GREEN, randomtarget))
except ValueError:
randomtarget = choice(listica)
randomtargetreal = org.bukkit.Bukkit.getPlayer(randomtarget)
if event.getPlayer().getLocation() != randomtargetreal.getLocation():
event.getPlayer().teleport(randomtargetreal)
event.getPlayer().sendMessage("%sYou teleported to: %s%s"%(bukkit.ChatColor.GREEN, bukkit.ChatColor.DARK_GREEN, randomtarget))
What I want is:
run for loop:
when there is no more players to add a.k.a it finishes
do try loop
P.S. I can't do it in separate function.
Thanks in advance! :)
Do you mean:
def func(args):
for item in loop:
do something
try: # note indentation
something else

Best Python way to harvest user entropy from keystrokes a la PGP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Does anyone recall PGP prompting a user to "generate some entropy" by striking random keys?
PGP would measure the entropy as it was being collected, indicating to the user with a cool little progress bar, and internally would time the key strokes, do some processing and use this as a seed for something or other.
I want to make a quick routine (console app) that does a similar "entropy collection" step in python, but I'm at a loss regarding a number of issues :
Best method of timing
Best method of collecting individual keystrokes
Best method to display cool progress bar back to user
Ideas about processing step, or actual details of the PGP step.
Best in the above means :
Tightest cleanest code
Most accurate (as in timing to picosecond or something)
Most pythonic/functional and using the standard library
So yeah :
def gen_user_random():
from Fourganizical import pack8
import time,sys
print 'Hey there user, start a-bashing that keyboard to make some randomness.'
keystimes = []
lasttime = None
while len(keystimes) < 20:
key = getch()
timenow = (time.time() + time.clock())
if lasttime:
timesince = timenow-lasttime
keystimes.append(int(timesince*100000000000000000))
lasttime = timenow
print 'Check out this *nasty* random number you made!'
rnum = int(''.join([str(x) for x in keystimes]))
print rnum
print 'And OMG here is that *nasty* set of bytes it made!'
rbytes = pack8(rnum)
print
sys.stdout.write(''.join(rbytes))
print
print
return keystimes
This creates some really nasty randomness.
pack8 just takes an integer of any length and outputs it in radix 256 as a sequence of bytes.

Categories