What Python Module Should I Use For Updating? - python

Alright I've been using the time module for time.sleep(x) function for awhile... but I need something that won't pause the shell and so the user can continue using the program while it's counting.
To be more "specific" let's suppose I had a program that needed to wait 5 seconds before executing a function. In this time using the time.sleep() function the user can't type anything into the shell because it's sleeping. However, I need Python to "count the 5 seconds" in the background while the user is able to use the shell. Is this possible?

threading ? You should handle piece of your work in one worker and another separate worker where you would count or sleep with time.sleep
Here is an example that might help you understand and use threading with time.sleep
import threading
import time
def sleeper():
print 'Starting to sleep'
time.sleep(10)
print 'Just waking up..'
print 'snooze'
print 'oh no. I have to get up.'
def worker():
print 'Starting to work'
time.sleep(1) # this also a work. :)
print 'Done with Work'
t = threading.Thread(name='sleeper', target=sleeper)
w = threading.Thread(name='worker', target=worker)
w.start()
t.start()

Related

How to allow a user a specified amount of time on a python program

Im pretty independent when using oython since i wouldnt consider myself a beginner etc, but Iv been coding up a program that I want to sell. The problem is that I want the program to have a timer on it and when it runs out the program will no longer work. Giving the user a specified amount of time they have to use the program.
You will want to run your program from another program using multithreading or asynchronous stuff. If you are looking for a single thing to send to your program (here, an interruption signal), then you should take a look at the signal built in package (for CPython).
(based on this answer from another post)
If you're calling external script using subprocess.Popen, you can just .kill() it after some time.
from subprocess import Popen
from time import sleep
with Popen(["python3", script_path]) as proc:
sleep(1.0)
proc.kill()
Reading documentation helps sometimes.
One way this can be done by interrupting the main thread
from time import sleep
from threading import Thread
from _thread import interrupt_main
import sys
TIME_TO_WAIT = 10
def kill_main(time):
sleep(time)
interrupt_main()
thread = Thread(target=kill_main, args=(TIME_TO_WAIT,))
thread.start()
try:
while True:
print('Main code is running')
sleep(0.5)
except KeyboardInterrupt: print('Time is up!')
sys.exit()

Python threads and strings

I am new to threads and multiprocessing. I have some code in which I start a process and I wanted the output to show an active waiting state of something like this
wating....
The code is similiar to this below:
import threading
import time
class ThreadExample(object):
def __init__(self):
self.pause = True
threading.Thread(target=self.second_thread).start()
# Some other processes
print("Waiting", end="")
while self.pause:
time.sleep(1)
print(".", end="")
print("Hooray!")
def second_thread(self):
print("timer started")
time.sleep(3)
self.pause = False
print("timer finished")
if __name__ == "__main__":
ThreadExample()
When I run the code above, I receive the output:
timer started
Do something else..timer finished
.
Hooray!
not a big surprise, except that only the 'timer started' appears at the beginning and the rest of the text appears in an instant at the end.
If I change the line print(".", end="") to print("."), I receive the following output:
timer started
Do something else.
.
timer finished
.
Hooray
where the dots appear in 1 second increments, which was my intention.
Is there a way to get the 'Waiting...' on one line without the end=""?
And secondly I am guessing this is something to do with the internals of the print() function, and if not, should I perform the threading in another manner? I do not think the problem is the GIL as I have tried multiprocess.Process and got the same result.
This is probably due to print buffering. It is flushed on \n and on some other occasions (like buffer overflow or program exit). Instead of print try this:
import sys
def unbuffered_print(msg):
sys.stdout.write(msg)
sys.stdout.flush()
...
unbuffered_print('.')
everywhere.

Kill process using another process python multiprocessing

I'm trying to create a script in Python. The idea is to start 3 processes, 2 of them constantly print a message, and the third is there to kill them after a few seconds. The problem is that I don't know how to tell that third which processes should be terminated.
from multiprocessing import *
import time
def OkreciLevi():
while 1:
print "okrecem levi"
time.sleep(3)
def OkreciDesni():
while 1:
print "okrecem desni"
time.sleep(3)
def Koci(levi,desni):
for vrednost in range(2):
print str(vrednost)
time.sleep(3)
levi.terminate()
desni.terminate()
print "kocim"
if __name__== '__main__':
levi=Process(target=OkreciLevi)
desni=Process(target=OkreciDesni)
koci=Process(target=Koci, args=(levi,desni))
koci.start()
levi.start()
desni.start()
levi.join()
desni.join()
koci.join()
Assuming that you're on *nix-like operating system I guess that you need to:
Get the PID of the multiprocessing worker;
Send SIGTERM to them. For instanse use os.kill.
Also this information may be useful for you.

How do i make a keypress display how long my program has been running?

import time
number = 1
while number > 0:
print "Testing"
time.sleep(5) #print every 5 seconds
That is just an example loop. I'm a semi-beginner and I'm not sure how to make a keypress(any key is fine) display how long the program has been running. This program will be running on Windows 7 and Linux.
Thank you very much.
Welcome to Stack Overflow and to Python! You'll like it here.
First, I'll show you how to print out the time your code has been running. The time module includes a time() function that gets the current time as a Unix timestamp (the number of seconds since January 1, 1970). If you assign it to a variable at the start of the function, you can simply call it each time through the loop and subtract it from the current time to get your runtime. With me so far?
(You can also remove your number variable and the number > 0 check and simply replace it with True.)
import time
start_time = time.time()
while True:
print "I've been running for %d seconds!" % (time.time() - start_time)
time.sleep(5) #print every 5 seconds
But you asked how to get it each time the user presses a key. If you just want 'enter', you can do:
import time
start_time = time.time()
while True:
print "I've been running for %d seconds!" % (time.time() - start_time)
raw_input("Press Enter...")
The raw_input() function will wait for the user to press Enter, then print out the runtime.
One problem at a time.
How do you find how long your program has been running at the point at which you want to calculate?
How do you detect a key-press?
How do you get the program to produce 1) when 2) happens?
Try each problem in turn, then ask if you need help.
There are a lot of complexities and approaches for a such a simple question.
If you are looking for up time of a currently running process, use the OS to query that process with the subprocess module to run a command line operation such as 'ps | grep "foo" '
Usually programs do only one thing at a time. For example, the code could either do work OR look for a keypress. If you need to run have to run two different sections of code concurrently, spawn (run) the code segments as separate threads . For your question you could spawn two threads (pieces of code), one to do work and one to query up time.
Use the threading module in python to wrap the worker function and create a query thread. However, when the worker thread is done, you will want the query thread to terminate also. One way to do this is to define it as a daemon thread. Daemon threads terminate when they are the only threads alive.
For example:
from time import sleep
import datetime
import threading
def do_someting():
MAX_RUN_TIME = 300 #Seconds
for i in xrange(MAX_RUN_TIME):
print i,
sleep (1)
class worker_thread(threading.Thread):
def run(self):
do_someting()
class keypress_daemon_thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self) # Initialize the parent class
self.daemon = True # Terminates if only daemon threads are left
def run(self):
startTime = datetime.datetime.now()
while True:
raw_input()
timeDelta = datetime.datetime.now() - startTime
print 'Up for', timeDelta
if __name__ == '__main__':
workerThread = worker_thread()
keyPressThread = keypress_daemon_thread()
workerThread.start()
keyPressThread.start()
workerThread.join()

Why print operation within signal handler may change deadlock situation?

I got simple program as below:
import threading
import time
import signal
WITH_DEADLOCK = 0
lock = threading.Lock()
def interruptHandler(signo, frame):
print str(frame), 'received', signo
lock.acquire()
try:
time.sleep(3)
finally:
if WITH_DEADLOCK:
print str(frame), 'release'
lock.release()
signal.signal(signal.SIGINT, interruptHandler)
for x in xrange(60):
print time.strftime("%H:%M:%S"), 'main thread is working'
time.sleep(1)
So, if you start that program and even Ctrl+C is pressed twice within 3 seconds, there is no deadlock. Each time you press Ctrl + C proper line is displayed.
If you change WITH_DEADLOCK=1 and you would press Ctrl+C twice (withing 3 seconds) then program will be hung.
Does anybody may explain why print operation make such difference?
(My python version is 2.6.5)
To be honest I think J.F. Sebastian's comment is the most appropriate answer here - you need to make your signal handler reentrant, which it currently isn't, and it is mostly just surprising that it works anyway without the print statement.

Categories

Resources