Have a running clock on terminal during python script execution - python

I'd like to, while my program is running, have a clock running in the console. Is it possible ?
Thanks !

You can run the following snippet in a separate thread/process:
from __future__ import print_function
import time
import sys
import datetime
while True:
now = datetime.datetime.now()
print(now.strftime("%H:%M:%S"), end="\r")
sys.stdout.flush()
time.sleep(.4)

Related

Why my app keep opening when I use shortcut in Python?

I tried to create a program to open a app with a specific shortcut but when I press my keys it keep opening and didn't stop until I stopped the program
import keyboard
import time
import subprocess
while True:
if keyboard.is_pressed('ctrl+space+b'):
subprocess.Popen([r"C:\\Program Files\\Everything\\Everything.exe"])
time.sleep(1.5)
How about try this code
import keyboard
import subprocess
import threading
def run_my_program():
subprocess.run([r"C:\Program Files\Everything\Everything.exe"])
while True:
if keyboard.is_pressed('ctrl+space+b'):
threading.Thread(target=run_my_program).start() # launch up the subprocess in parallel so input is not delayed
while keyboard.is_pressed('ctrl+space+b'):
pass # Wait until user lifts his hands off the keyboard

Updating lines in terminal while doing other stuff on the last one in Python?

I am trying to write a Python program that tracks the prices of the stock market and outputs it to the user refreshing the same line through stderr, that's a simplified version of the code (used randint just to check that the program was doing something):
import random
import schedule
import time
import sys
def printran():
a = "\rFirst Line is: " + str(random.randint(1,10))
sys.stderr.write(a)
schedule.every(2).seconds.do(printran)
while True:
schedule.run_pending()
time.sleep(1)
My problems are:
a) How do I "refresh"the console output on multiple lines?
I tried stuff like:
a = "\rFirst Line is: " + str(random.randint(1,10)) + "\n\rSecond Line is: " + str(random.randint(2,20))
but the output is a mess and obviously the \n command will always generate a new line
b) since the while function doesn't really end I cannot do other stuff, do I need to use multithreading?
c) finding a solution that is as much as possible easy, portable and OS agnostic (must work on Linux, OSX, Win).
import random
import schedule
import threading
import time
def printran():
print("First Line is: " + str(random.randint(1,10)))
def run():
schedule.every(2).seconds.do(printran)
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
t = threading.Thread(target=run)
t.start()
Also, you can use APScheduler
But in the following code sched.start() won't wait and it will stop with main.
import random
from apscheduler.schedulers.background import BackgroundScheduler
import time
def printran():
print("First Line is: " + str(random.randint(1,10)))
if __name__ == "__main__":
sched = BackgroundScheduler()
sched.add_job(printran, 'interval', seconds=2)
sched.start()
# wait 10 seconds and exit
time.sleep(10)
Should be crossplatform (I didn't check on Win, Mac, but it works on linux)

how to make timer for quiting from python3

I have a script and it doesn't work proper, so in bash I let script in while loop and I wanna my script can close itself after a while, I tried to use threading.timer but my code wont run quit() or exit() command, could anyone please help me?
#!/usr/bin/env python3
import threading
from time import sleep
def qu():
print("bye")
exit()
t=threading.Timer(5.0,qu)
t.start()
while(True):
sleep(1)
print("hi")
You could use the os._exit function instead of exit()
Getting the code as follows:
#!/usr/bin/env python3
import threading
import os
from time import sleep
def qu():
print("bye")
os._exit(0)
t=threading.Timer(5.0,qu)
t.start()
while(True):
sleep(1)
print("hi")
Anyways I would suggest you to checkout this question as it is similar to yours.

Verifying that an APScheduler task has properly executed

I'm trying to use the APScheduler library to execute a job at two certain times: 1am PST and 2am PST.
Sort of lost, I am trying to figure out what am doing wrong. Here is my code so far:
#!/usr/bin/python
import sys
import re
import urllib
import csv
import urllib2
import logging
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
logging.basicConfig()
def main():
#Make a rest call, store the output in a csv, close the file.
...
f.close()
sched.add_job(my_job, 'date', run_date = '2015-12-15 01:00:00', args=['text'])
try:
sched.start()
print(datetime.datetime.now())
except (KeyboardInterrupt):
logger.debug('Terminating...')
print (datetime.datetime.now())
The current time is 12:16 PST, I just ran the above script and it executed and created the file prior to the job time of 12:30:30pm; this is for testing purposes.
So, I'm trying to figure out what I am doing wrong with regards to using APScheduler.
I want to improve this code, what are some things I can change?
If you want to run your code at certain times every time, you should be using the cron trigger:
sched.add_job(my_job, 'cron', hour='1,2', args=['text'])
For better debugging:
logging.basicConfig(level=logging.DEBUG)

Strange problems when using requests and multiprocessing

Please check this python code:
#!/usr/bin/env python
import requests
import multiprocessing
from time import sleep, time
from requests import async
def do_req():
r = requests.get("http://w3c.org/")
def do_sth():
while True:
sleep(10)
if __name__ == '__main__':
do_req()
multiprocessing.Process( target=do_sth, args=() ).start()
When I press Ctrl-C (wait 2sec after run - let Process run), it doesn't stop. When I change the import order to:
from requests import async
from time import sleep, time
it stops after Ctrl-C. Why it doesn't stop/kill in first example?
It's a bug or a feature?
Notes:
Yes I know, that I didn't use async in this code, this is just stripped down code. In real code I use it. I did it to simplify my question.
After pressing Ctrl-C there is a new (child) process running. Why?
multiprocessing.__version__ == 0.70a1, requests.__version__ == 0.11.2, gevent.__version__ == 0.13.7
Requests async module uses gevent. If you look at the source code of gevent you will see that it monkey patches many of Python's standard library functions, including sleep:
request.async module during import executes:
from gevent import monkey as curious_george
# Monkey-patch.
curious_george.patch_all(thread=False, select=False)
Looking at the monkey.py module of gevent you can see:
https://bitbucket.org/denis/gevent/src/f838056c793d/gevent/monkey.py#cl-128
def patch_time():
"""Replace :func:`time.sleep` with :func:`gevent.sleep`."""
from gevent.hub import sleep
import time
patch_item(time, 'sleep', sleep)
Take a look at the code from the gevent's repository for details.

Categories