This is my script, it takes screenshots after 5 seconds and stores it into a png file with timestamp as its name.
I want this script to run between 9am to 5pm everyday so i could get screenshot f every activity done between 9 to 5 every day.
import pyautogui
import time
for i in range(4):
# Take screensot
pic = pyautogui.screenshot()
#Name the file with data and time
ts = time.strftime("%Y%m%d-%H%M%S")
filename = "screenshot"
filename += str(ts)
filename += ".png"
# Save the image
pic.save('C:\\Users\\DELL\\Desktop\\Frankiii\{}'.format(filename))
time.sleep(5)
Here is how you could do it.
import schedule
def start():
print("{} Start the job".format(datetime.datetime.now()))
def stop():
print("{} Time's up!!!".format(datetime.datetime.now()))
sys.exit()
schedule.every().day.at("09:00").do(start)
schedule.every().day.at("17:00").do(stop)
Related
How to show text when certain time comes
Such as when the time to 0:30:0 will display the text
import time
def countdown(time_sec):
time_msec = time_sec*10
while time_msec:
mins, secs = divmod(time_msec, 600)
secs, msecs = divmod(secs, 10)
timeformat = "{:02d}:{:02d}.{:01d}".format(mins, secs, msecs)
print(timeformat, end='\r')
time.sleep(1/10)
time_msec -= 1
print("stop")
countdown(61)
I can show you an example I coded some time ago, which displays a message every time the clocl hits 30 seconds.
import datetime
import time
# set the target time to 30 seconds
target_seconds = 30
while True:
# get the current time in seconds
current_seconds = datetime.datetime.now().time().second
# check if the current time matches the target time
if current_seconds == target_seconds:
print("It's time!")
# wait for 1 second before checking the time again
time.sleep(1)
you should be able to adapt it for your needs. Basically you do an if cluase that checks if your target time has come.
We can eliminate that remote possibility of 'skipping' by making clock independent. A modified version of #fallouthase :
import datetime
import time
target_seconds = 30
def print_str(time):
if time==target_seconds:
print("Its time")
def time_call(time):
print(current_seconds)
while True:
current_seconds = datetime.datetime.now().time().second
time_call(current_seconds)
print_str(current_seconds)
time.sleep(1)
My aim is to send an image file in whatsapp to various persons who are not on my contact list. Try with pywhatkit. Store the number in an excel sheet and read it by pandas. Loop the number to send the image file. The first number gets the image file successfully, and the remaining numbers WhatsApp will open but the message will not send. Also tell, me how to avoid WhatsApp open in a new tab(chrome)every time.
Here's my code
import pandas as pd
file_name = r'd:\\Recipients data.xlsx'
df = pd.read_excel(file_name)
contact = df['Contact'].tolist()
import pywhatkit
import time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M : %S")
h,m,s = current_time.split(':')
print(now)
h1 = int(h)
m1 = int(m)
s1 = int(s)
file_path = r'C:/Users/Asus/Downloads/subadev.jpeg'
for send_number in contact:
new_format = (f'"{str("+91")+str(send_number)}"')
print(new_format)
pywhatkit.sendwhats_image(new_format,file_path)
time.sleep(15)
expecting : send images to every number without open whats app every time
I have 1,440 audio files to feed into a neural network. The problem is that they are not all the same length. I used the answer posted on:
Adding silent frame to wav file using python
but it doesn't seem to work. I wanted to add a few seconds of silence to the end of my files, and then trim them to all be 5 seconds long. Can someone please help me with this?
(I also tried using pysox, but that gives me the This install of SoX cannot process .wav files. error.)
I am using Google Colab for this. The code is:
import wave, os, glob
from pydub import AudioSegment
from pydub.playback import play
path = 'drive/MyDrive/Ravdess/Sad' #This is the folder from my Google Drive which has the audio files
count = 0
for filename in glob.glob(os.path.join(path, '*.wav')):
w = wave.open(filename, 'r')
d = w.readframes(w.getnframes())
frames = w.getnframes()
rate = w.getframerate()
duration = frames/float(rate)
count+=1
print(filename, "count =", count, "duration = ", duration)
audio_in_file = filename
audio_out_file = "out.wav"
new_duration = duration
#Only append silence until time = 5 seconds.
one_sec = AudioSegment.silent(duration=2000) #duration in milliseconds
song = AudioSegment.from_wav(audio_in_file)
final_song = one_sec + song
new_frames = w.getnframes()
new_rate = w.getframerate()
new_duration = new_frames/float(rate)
final_song.export(audio_out_file, format="wav")
print(final_song, "count =", count, "new duration = ", new_duration)
w.close()
This gives the output:
drive/MyDrive/Ravdess/Sad/03-01-04-01-02-01-01.wav count = 1 duration = 3.5035
<pydub.audio_segment.AudioSegment object at 0x7fd5b7ca06a0> count = 1 new duration = 3.5035
drive/MyDrive/Ravdess/Sad/03-01-04-01-02-02-01.wav count = 2 duration = 3.370041666666667
<pydub.audio_segment.AudioSegment object at 0x7fd5b7cbc860> count = 2 new duration = 3.370041666666667
... (and so on for all the files)
Since you are already using pydub, I'd do something like this:
from pydub import AudioSegment
from pydub.playback import play
input_wav_file = "/path/to/input.wav"
output_wav_file = "/path/to/output.wav"
target_wav_time = 5 * 1000 # 5 seconds (or 5000 milliseconds)
original_segment = AudioSegment.from_wav(input_wav_file)
silence_duration = target_wav_time - len(original_segment)
silenced_segment = AudioSegment.silent(duration=silence_duration)
combined_segment = original_segment + silenced_segment
combined_segment.export(output_wav_file, format="wav")
I'm very new to Python (with most of my previous programming experience being in intermediate C++ and Java) and am trying to develop a script which will read sensor data and log it to a .csv file. To do this I created separate classes for the code-- one will read the sensor data and output it to the console, while the other is supposed to take that data and log it-- and combined them together into a master script containing each class. Separately, they work perfectly, but together only the sensorReader class functions. I am trying to get each class to run in its own thread, while passing the sensor data from the first class (sensorReader) to the second class (csvWriter) as well. I've posted some of my pseudocode below, but I'd be happy to clarify any questions with the actual source code if needed.
import time
import sensorStuff
import csv
import threading
import datetime
class sensorReader:
# Initializers for the sensors.
this.code(initializes the sensors)
while True:
try:
this.code(prints the sensor data to the console)
this.code(throws exceptions)
this.code(waits 60 seconds)
class csvWriter:
this.code(fetches the date and time)
this.code(writes the headers for the excel sheet once)
while True:
this.code(gets date and time)
this.code(writes the time and one row of data to excel)
this.code(writes a message to console then repeats every minute)
r = sensorReader()
t = threading.Thread(target = r, name = "Thread #1")
t.start()
t.join
w = csvWriter()
t = threading.Thread(target = w, name = "Thread #2")
t.start()
I realize the last part doesn't really make sense, but I'm really punching above my weight here, so I'm not even sure why only the first class works and not the second, let alone how to implement threading for multiple classes. I would really appreciate it if anyone could point me in the right direction.
Thank you!
EDIT
I've decided to put up the full source code:
import time
import board
import busio
import adafruit_dps310
import adafruit_dht
import csv
import threading
import datetime
# import random
class sensorReader:
# Initializers for the sensors.
i2c = busio.I2C(board.SCL, board.SDA)
dps310 = adafruit_dps310.DPS310(i2c)
dhtDevice = adafruit_dht.DHT22(board.D4)
while True:
# Print the values to the console.
try:
global pres
pres = dps310.pressure
print("Pressure = %.2f hPa"%pres)
global temperature_c
temperature_c = dhtDevice.temperature
global temperature_f
temperature_f = temperature_c * (9 / 5) + 32
global humidity
humidity = dhtDevice.humidity
print("Temp: {:.1f} F / {:.1f} C \nHumidity: {}% "
.format(temperature_f, temperature_c, humidity))
print("")
# Errors happen fairly often with DHT sensors, and will occasionally throw exceptions.
except RuntimeError as error:
print("n/a")
print("")
# Waits 60 seconds before repeating.
time.sleep(10)
class csvWriter:
# Fetches the date and time for future file naming and data logging operations.
starttime=time.time()
x = datetime.datetime.now()
# Writes the header for the .csv file once.
with open('Weather Log %s.csv' % x, 'w', newline='') as f:
fieldnames = ['Time', 'Temperature (F)', 'Humidity (%)', 'Pressure (hPa)']
thewriter = csv.DictWriter(f, fieldnames=fieldnames)
thewriter.writeheader()
# Fetches the date and time.
while True:
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
# Writes incoming data to the .csv file.
with open('Weather Log %s.csv', 'a', newline='') as f:
fieldnames = ['TIME', 'TEMP', 'HUMI', 'PRES']
thewriter = csv.DictWriter(f, fieldnames=fieldnames)
thewriter.writerow({'TIME' : current_time, 'TEMP' : temperature_f, 'HUMI' : humidity, 'PRES' : pres})
# Writes a message confirming the data's entry into the log, then sets a 60 second repeat cycle.
print("New entry added.")
time.sleep(10.0 - ((time.time() - starttime) % 10.0)) # Repeat every ten seconds.
r = sensorReader()
t = threading.Thread(target = r, name = "Thread #1")
t.start()
t.join
w = csvWriter()
t = threading.Thread(target = w, name = "Thread #2")
t.start()
It would work better structured like this. If you put the first loop in a function, you can delay its evaluation until you're ready to start the thread. But in a class body it would run immediately and you never get to the second definition.
def sensor_reader():
# Initializers for the sensors.
this.code(initializes the sensors)
while True:
try:
this.code(prints the sensor data to the console)
except:
print()
this.code(waits 60 seconds)
threading.Thread(target=sensor_reader, name="Thread #1", daemon=True).start()
this.code(fetches the date and time)
this.code(writes the headers for the excel sheet once)
while True:
this.code(gets date and time)
this.code(writes the time and one row of data to excel)
this.code(writes a message to console then repeats every minute)
I made it a daemon so it will stop when you terminate the program. Note also that we only needed to create one thread, since we already have the main thread.
I'm writing a python script to screenshot every 30 seconds and save the output image with the actual date.
The problem is that the script is saving each image with each letter of the time.ctime() output (Tue Jan 3 01:30:53 2017):
T.png
u.png
e.png
...
How can i save each image output with the actual complete date ?
import pyscreenshot as ImageGrab
import time
max_prints = 10
counter = 0
timer = time.ctime()
while counter < max_prints:
for mark in timer:
im=ImageGrab.grab()
#im.show()
im=ImageGrab.grab(bbox=(10,10,500,500))
#im.show()
ImageGrab.grab_to_file(str(mark) + ".png")
time.sleep(30)
This loop may help:
while counter < max_prints:
im = ImageGrab.grab(bbox=(10, 10, 500, 500))
filename = str(dt.datetime.now()).replace(' ', 'T').split('.')[0] + ".png"
ImageGrab.grab_to_file(filename)
time.sleep(5)
Can you try with something like thisĀ ?
import pyscreenshot as ImageGrab
import time
max_prints = 10
counter = 0
while counter < max_prints:
im=ImageGrab.grab()
#im.show()
im=ImageGrab.grab(bbox=(10,10,500,500))
#im.show()
timer = time.ctime()
ImageGrab.grab_to_file(timer + ".png")
time.sleep(30)
counter += 1
If you want to you could have filenames that will be easier to handle afterward by changing these lines:
timer = time.ctime()
ImageGrab.grab_to_file(timer + ".png")
To this:
timer = time.ctime()
timestamp = timer.replace(' ', '_')
timestamp = timestamp.replace(':', '_')
filename = "{}.png".format(timestamp)
ImageGrab.grab_to_file(filename)
But it depends on how you want your files to be named.