Python save multiple images with pyautogui - python

Im making a screenshot program that takes a screenshot every 5 seconds. But it will only save 1 .png file. Its becuase the name is the same every time and it wont make duplicates.
How do i save them as image(1), image(2), image(3)....
This is my code:
import pyautogui
import threading
#myScreenshot = pyautogui.screenshot()
#myScreenshot.save(r'C:\Users\censored\Desktop\screenshot\imgs\image.png')
def ScreenShotTimer():
threading.Timer(5.0, ScreenShotTimer).start()
myScreenshot = pyautogui.screenshot()
myScreenshot.save(r'C:\Users\censored\Desktop\screenshot\imgs\image.png')
print('Program Is Still Running.')
ScreenShotTimer()
Thanks for helping me!

import pyautogui
# Solution 1
import time
for i in range(60):
ss = pyautogui.screenshot()
ss.save(f"SS {i}.png")
time.sleep(5)
# Solution 2
import threading
import functools as ft
def screenshot(index: int = 0):
ss = pyautogui.screenshot()
ss.save(f"SS {index}.png")
threading.Timer(5.0, ft.partial(screenshot, index+1)).start()
screenshot()
Two solutions.
Uses a for loop (could easily be a while loop).
Uses threading.Timer and functools.partial to call the
function again, with a different parameter.

Related

Python, how to execute a line of code without it stopping the rest of the code from executing?

first of all, im a beginner.
Want i want to accomplish is that music plays while the script is executing.
What it does right now it plays the music, waits until the music is over and then executes the rest of the code. That is not what i want. Here my Code:
import os
import subprocess
import multiprocessing
import threading
from playsound import playsound
CurrentPath = os.path.dirname(os.path.normpath(__file__))
os.chdir(CurrentPath)
def music():
Music = "Music.mp4"
#subprocess.run(["ffplay", "-nodisp", "-autoexit", "-hide_banner", Music])
playsound("Music.mp4")
def other_things():
print("Hello World")
#musicp = multiprocessing.Process(target=music())
#restp = multiprocessing.Process(target=other_things())
musicp = threading.Thread(target=music())
restp = threading.Thread(target=other_things())
restp.start()
musicp.start()
LIke you can see i even tried multithreading but it still waits until the music is over before it goes to the rest of the code.
Don't call the functions in the target parameter of the Thread function - delete the brackets to reference the function, not its return value
musicp = threading.Thread(target=music) # instead of music()
restp = threading.Thread(target=other_things) # instead of other_things()

Input() and threading

I'm trying to create application which needs to get user input data while it prints things in a console at the same time.
import threading
import time
def F1():
for i in range (100):
print (i)
time.sleep(1)
def input_data():
txt = input('>')
print(txt)
w1 = threading.Thread(target=F1)
w2 = threading.Thread(target=input_data)
w1.start()
w2.start()
But this way function input() stops all threads.
Is it possible to do it asynchronously in a python interpreter?
(I know that i could do it in tkinter easily.)

Pyautogui : Autoclicker with Image recognition How do I make a function I made only run if an image is recognised?

I'm new in python and I know my code is really messy . I need help , I wanted the function below to only run If an Image I set is recognised mc_ok_button.png but it's kind of confusing because I want it to join with a loop I already made . If I place the code in the loop wouldn't it not run the rest of the functions below it ?
My image recognition function :
import pyautogui as pg
import pydirectinput as pd
import time
ax,ay = pg.locateCenterOnScreen('mc_ok_button.png',confidence=.6)
def function_when_restart():
print(ax,ay)
pd.click(ax,ay)
print('Waiting to return back to the server...')
time.sleep(8)
pd.moveTo(892,531)
print('finding server...')
pd.click()
print('connecting to the server...')
function_when_restart()
Then I want the function_when_restart() function to only run if the mc_ok_button.png image is recognised and make project() and fix_tool() stop while function_when_restart() is running then continue back to make project() and fix_tool() :
from time import monotonic
from time import monotonic, sleep
start = monotonic()
while monotonic() - start < (60) : #Run for exactly 1 minute
# I want the image recognition to always run and if the image pops up I want
project()
sleep(5)
fix_tool()
below can help?
while True:
image = pyautogui.locateOnScreen('image.png')
if image != None:
project()
sleep(5)
fix_tool()
else:
pass

How to make Python wait while QGIS renders a shapefile

I have written code for my QGIS 2.8.1 which can successfully take screenshot of one shape file, but unfortunately it doesn't work when I try with multiple shapefiles.
So basically if I replace allFiles = ["C:/Shapefiles/Map_00721.shp"] in the code below with allFiles = ["C:/Shapefiles/Map_00721.shp", "C:/Shapefiles/Map_00711.shp", "C:/Shapefiles/Map_00731.shp", "C:/Shapefiles/Map_00791.shp", "C:/Shapefiles/Map_00221.shp"], the loop iterates over the array without waiting for the rendering and snapshot process to happen.
I have tried using time.sleep in the code below, but it stops the rendering of shapefiles too and the result doesn't came as expected.
import ogr,os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
import qgis.utils
import glob
from time import sleep
import math
import processing
from processing.core.Processing import Processing
from PyQt4.QtCore import QTimer
Processing.initialize()
Processing.updateAlgsList()
OutputFileName = "ABC" # Temprory global placeholder for filename
canvas = iface.mapCanvas()
def startstuffs():
qgis.utils.iface.zoomToActiveLayer() # Zoom to Layer
scale=canvas.scale() # Get current Scale
scale = scale * 1.5
canvas.zoomScale(scale) # Zoomout a bit
QTimer.singleShot(2000,saveImg) # Jump to save img
def saveImg():
qgis.utils.iface.mapCanvas().saveAsImage(OutputFileName)
QgsMapLayerRegistry.instance().removeAllMapLayers()
# Add array of address below
allFiles = ["C:/Shapefiles/Map_00721.shp"]
filesLen = len(allFiles)
TexLayer = "C:/US_County_NAD27.shp"
for lop in range(filesLen):
currentShpFile = allFiles[lop]
currentShpFileName = currentShpFile.strip("C:/Shapefiles/")
OutputFileName = "C:/ImageOut/" + currentShpFileName + ".png"
wb = QgsVectorLayer(currentShpFile, currentShpFileName, 'ogr')
wbTex = QgsVectorLayer(TexLayer, 'CountyGrid', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(wb) # Add the shapefile
QgsMapLayerRegistry.instance().addMapLayer(wbTex) # Add the county shapefile
qgis.utils.iface.setActiveLayer(wb) # Makes wb as active shapefile
QTimer.singleShot(3000, startstuffs) # This start stuffs
print "Done!"
Avoid using time.sleep() since that will completely stall your entire program. Instead, use processEvents() which allows your program to render in the background.
import time
def spin(seconds):
"""Pause for set amount of seconds, replaces time.sleep so program doesn't stall"""
time_end = time.time() + seconds
while time.time() < time_end:
QtGui.QApplication.processEvents()
This method should work fine for a quick fix, but in the long term it may generate difficult problems to track. It is better to use a QTimer with a event loop for a permanent solution.

Update variable from imported module with Python when using Threading

In a project, I would like to separate the visualization and calculation in two different modules. The goal is to transfer the variables of the calculation-module to a main-script, in order to visualize it with the visualization-script.
Following this post
Using global variables between files?,
I am able to use a config-script in order to transfer a variable between to scripts now. But unfortunately, this is not working when using threading. The Output of the main.py is always "get: 1".
Does anyone have an idea?
main.py:
from threading import Thread
from time import sleep
import viz
import change
add_Thread = Thread(target=change.add)
add_Thread.start()
viz.py:
import config
from time import sleep
while True:
config.init()
print("get:", config.x)
sleep(1)
config.py:
x = 1
def init():
global x
change.py:
import config
def add():
while True:
config.x += 1
config.init()
OK, fount the answer by myself. Problem was in the "main.py". One has to put the "import viz" after starting the thread:
from threading import Thread
from time import sleep
import change
add_Thread = Thread(target=change.add)
add_Thread.start()
import viz

Categories

Resources