Итак, у меня есть эти коды, они работали безупречно благодаря индивидуальному тестированию. Но когда я их объединяю, это больше не работает. Пожалуйста, профессионалы Python помогут новичку. Спасибо!
Шаги уже проверены.
Определение удалено. с участием только F1 и F2. Блокирует только эти коды.
Я даже пробовал использовать чатgpt, но он удаляет часть моего кода и больше не работает.
Заранее большое спасибо тем, кто мне поможет. Вы все добры.
Вот первый шаг, который я хочу сделать от сценария.
import pyautogui
import time
import keyboard # Import the keyboard library to listen for key presses
# Define the image path
sample = r"C:\Users\sample\Documents\sample\samplep.png"
# Get screen size
screen_width, screen_height = pyautogui.size()
# Define the right half of the screen (covering from the middle to the right edge)
region = (screen_width // 2, 0, screen_width // 2, screen_height)
def to_sample(sample, region):
"""Search for an image within a specified region and click it with an offset."""
try:
# Locate the image within the region with confidence of 0.7
location = pyautogui.locateCenterOnScreen(sample, region=region, confidence=0.7)
if location:
print(f"Found image at: {location}")
# Move cursor 43 pixels to the right and 50 pixels down from the found image center
new_x = location.x + 43
new_y = location.y + 50
# Move the cursor to the new position and click
pyautogui.moveTo(new_x, new_y)
pyautogui.click()
print(f"Moved cursor to new position ({new_x}, {new_y}) and clicked.")
return True # Return True indicating image found and clicked
else:
print("Image not found in the right half of the screen.")
return False
except pyautogui.ImageNotFoundException:
print("Image not found in the right half of the screen.")
return False
def to_test():
"""Main function to start and stop the loop with F1 and F2."""
print("Press F1 to start the loop and F2 to stop.")
while True:
# Wait for F1 to start the loop
if keyboard.is_pressed('F1'):
print("F1 pressed, starting the loop...")
# Search for the image only once
if to_sample(sample, region):
print("Image found and clicked!")
else:
print("Image not found. Waiting for F1 to start again.")
print("Press F2 to stop.")
while not keyboard.is_pressed('F2'): # Wait until F2 is pressed to stop
time.sleep(0.1) # Wait briefly to avoid CPU overload
print("F2 pressed, stopping the program.")
break # Exit the loop and stop the program
# Wait for F2 to stop the script
if keyboard.is_pressed('F2'):
print("F2 pressed, stopping the program.")
break # Exit the program if F2 is pressed
time.sleep(0.1) # Short delay to prevent high CPU usage
if __name__ == "__main__":
to_test()
Тогда следующий шаг моего кода должен сделать это
import pyautogui
import time
import keyboard # Import the keyboard library to listen for key presses
import os
# Define image paths
sample1_img = r"C:\Users\sample\Documents\sample\sample1.png"
sample2_img = r"C:\Users\sample\Documents\sample\sample2png"
sample3_img = r"C:\Users\sample\Documents\sample\sample3.png"
sample4_img = r"C:\Users\sample\Documents\sample\sample4.png"
sample5_img = r"C:\Users\sample\Documents\sample5\sample5.png"
sample6_img = r"C:\Users\sample\Documents\sample6\sample6.png"
sample7_img = r"C:\Users\sample\Documents\sample7\sample7.png"
sample8_img = r"C:\Users\sample\Documents\sample8\sample8.png"
sample9_img = r"C:\Users\sample\Documents\sample9\sample9.png"
def find_and_click_buy(image_path, confidence=0.8, retries=3):
"""Finds the image on the screen and clicks it if found, with retry logic."""
attempt = 0
while attempt < retries:
try:
location = pyautogui.locateCenterOnScreen(image_path, confidence=confidence)
if location:
pyautogui.click(location)
return True
else:
print(f"Image '{image_path}' not found, retrying...")
except pyautogui.ImageNotFoundException as e:
print(f"Image '{image_path}' not found on attempt {attempt + 1}.")
attempt += 1
time.sleep(1)
print(f"Failed to find image: {image_path} after {retries} attempts.")
return False
def to_buy():
"""Perform the entire process of buying."""
print("Starting the 'Buy' process.")
# Step 1: Keep searching for "sample1.png"
while True:
sample1_location = pyautogui.locateCenterOnScreen(sample1_img, confidence=0.8)
if sample1_location:
print("Found 'sample1.png', starting purchase process.")
# Step 2: Move cursor 60 pixels down from the center of "sample1.png" and right-click
pyautogui.moveTo(sample1_location.x, sample_location.y + 60)
pyautogui.rightClick()
time.sleep(1)
# Step 3: Look for "sample2.png" and click it
if find_and_click_buy(trade_img):
print("Clicked on 'sample2.png'.")
time.sleep(2)
# Step 4: Look for "sample3.png" and click it
if find_and_click_buy(sample3_img):
print("Clicked on 'sample3.png'.")
# Step 5: Move mouse to the center of the screen and scroll down
pyautogui.moveTo(pyautogui.size().width // 2, pyautogui.size().height // 2)
pyautogui.scroll(-1500)
# Step 6: Look for "sample4.png" while scrolling
if find_and_click_buy(sample4_img):
print("Clicked on 'sample4.png'.")
time.sleep(1)
# Step 7: Look for "sample8.png" and click it
if find_and_click_buy(sample8_img):
print("Clicked on 'sample8.png'.")
# Step 8: Look for "sample9.png" and click it
if find_and_click_buy(sample9_img):
print("Clicked on 'sample9.png'.")
# Step 9: Look for "sample5.png" and click it
if find_and_click_buy(sample5_img):
print("Clicked on 'sample5.png'.")
time.sleep(1)
# Step 10: Look for "sample4.png" and scroll down again while looking for "sample6.png"
if find_and_click_buy(sample4_img):
print("Clicked on 'sample4.png'.")
pyautogui.moveTo(pyautogui.size().width // 2, pyautogui.size().height // 2)
pyautogui.scroll(-1800)
# Step 11: Look for "sample6.png" while scrolling
if find_and_click_buy(_sample6_img, confidence=0.5): # Lower confidence for sample7
print("Clicked on 'sample7.png'.")
time.sleep(1)
# Step 12: Look for "sample8.png" and click it again
if find_and_click_buy(sample8_img):
print("Clicked on 'sample8.png' again.")
# Step 13: Look for "sample9.png" and click it again
if find_and_click_buy(sample9_img):
print("Clicked on 'sample9.png' again.")
time.sleep(1)
break # Exit the loop after completing the sequence
else:
print("Failed to find 'sample9.png' after.")
else:
print("Failed to find 'sample8.png' after")
else:
print("Failed to find 'sample6.png'.")
else:
print("Failed to find 'sample4.png'.")
else:
print("Failed to find 'sample5.png'.")
else:
print("Failed to find 'sample9.png'.")
else:
print("Failed to find 'sample8.png'.")
else:
print("Failed to find 'sample2.png'.")
else:
print("Failed to find 'sample2.png'.")
break # Exit the loop after completing the sequence
else:
print("Looking for 'sample1.png'...") # Keep searching for 'sample1.png' if not found
time.sleep(1) # Wait for 1 second before checking again
def main():
print("Press F1 to start the reagent buying process.")
print("Press F2 to stop the program at any time.")
while True:
# Wait for the user to press F1 to start the process
if keyboard.is_pressed('F1'):
print("F1 pressed, starting 'Buy Reagents' process...")
to_buy()
break # Exit after the process is completed
# Wait for the user to press F2 to stop the script
if keyboard.is_pressed('F2'):
print("F2 pressed, stopping the program.")
break # Exit the loop if F2 is pressed
time.sleep(0.1) # Add a short delay to prevent high CPU usage from constant checking
if __name__ == "__main__":
main()
Тогда это последний шаг:
import pyautogui
import time
import keyboard # Import the keyboard library to listen for key presses
# Define the image paths
goingapo_img = r"C:\Users\sample\Documents\sample\goingapo.png"
reagentprep_img = r"C:\Users\sample\Documents\sample\reagentpreparation.png" # Updated image name
clock_img = r"C:\Users\sample\Documents\sample\clock.png"
# Get screen size
screen_width, screen_height = pyautogui.size()
# Define the upper-right quadrant region for the "goingapo" image
region = (screen_width // 2, 0, screen_width // 2, screen_height // 2)
def find_and_click_reagent_prep(image_path, offset_y=0, region=None):
"""Locate an image on the screen, click on it, and apply an optional vertical offset."""
try:
# Locate the image on the screen or within a specific region
location = pyautogui.locateCenterOnScreen(image_path, region=region, confidence=0.8)
if location:
print(f"Found image: {image_path} at {location}")
# Calculate the new position with the vertical offset (downwards from the center)
new_x = location.x
new_y = location.y + offset_y
# Move the cursor to the new position and click
pyautogui.moveTo(new_x, new_y)
pyautogui.click()
print(f"Moved cursor to ({new_x}, {new_y}) and clicked.")
return True
else:
print(f"Image not found: {image_path}")
return False
except pyautogui.ImageNotFoundException:
print(f"Image not found: {image_path}")
return False
def main():
"""Main function that starts and stops the loop with F1 and F2."""
print("Press F1 to start the loop and F2 to stop.")
while True:
# Wait for F1 to start the loop
if keyboard.is_pressed('F1'):
print("F1 pressed, starting the loop...")
# Step 1: Look for "goingapo.png" image in the upper-right quadrant and click
if find_and_click_reagent_prep(goingapo_img, region=region):
print("Image 'goingapo.png' found and clicked!")
# Step 2: Wait for 15 seconds before searching for reagentprep_img
print("Waiting for 15 seconds...")
time.sleep(15)
# Step 3: Look for "reagentprep_img.png" and click 40px down from the center
if find_and_click_reagent_prep(reagentprep_img, offset_y=40):
print("Image 'reagentprep_img.png' found and clicked!")
# Step 4: Look for "clock.png" and click
if find_and_click_reagent_prep(clock_img):
print("Image 'clock.png' found and clicked!")
else:
print("Failed to find 'clock.png'.")
else:
print("Failed to find 'reagentprep_img.png'.")
else:
print("Failed to find 'goingapo.png'.")
print("Press F2 to stop.")
# Wait until F2 is pressed to stop the program
while not keyboard.is_pressed('F2'):
time.sleep(0.1) # Wait briefly to avoid CPU overload
print("F2 pressed, stopping the program.")
break # Exit the program after pressing F2
# Wait for F2 to stop the script
if keyboard.is_pressed('F2'):
print("F2 pressed, stopping the program.")
break # Exit the program if F2 is pressed
time.sleep(0.1) # Short delay to prevent high CPU usage
if __name__ == "__main__":
main()
Подробнее здесь: https://stackoverflow.com/questions/792 ... -functions
Объединение скриптов Python в один, не влияющий на их функции ⇐ Python
Программы на Python
-
Anonymous
1732589474
Anonymous
[b]Итак, у меня есть эти коды, они работали безупречно благодаря индивидуальному тестированию. Но когда я их объединяю, это больше не работает. Пожалуйста, профессионалы Python помогут новичку. Спасибо![/b]
Шаги уже проверены.
Определение удалено. с участием только F1 и F2. Блокирует только эти коды.
Я даже пробовал использовать чатgpt, но он удаляет часть моего кода и больше не работает.
[b]Заранее большое спасибо тем, кто мне поможет. Вы все добры.[/b]
[b]Вот первый шаг, который я хочу сделать от сценария.[/b]
import pyautogui
import time
import keyboard # Import the keyboard library to listen for key presses
# Define the image path
sample = r"C:\Users\sample\Documents\sample\samplep.png"
# Get screen size
screen_width, screen_height = pyautogui.size()
# Define the right half of the screen (covering from the middle to the right edge)
region = (screen_width // 2, 0, screen_width // 2, screen_height)
def to_sample(sample, region):
"""Search for an image within a specified region and click it with an offset."""
try:
# Locate the image within the region with confidence of 0.7
location = pyautogui.locateCenterOnScreen(sample, region=region, confidence=0.7)
if location:
print(f"Found image at: {location}")
# Move cursor 43 pixels to the right and 50 pixels down from the found image center
new_x = location.x + 43
new_y = location.y + 50
# Move the cursor to the new position and click
pyautogui.moveTo(new_x, new_y)
pyautogui.click()
print(f"Moved cursor to new position ({new_x}, {new_y}) and clicked.")
return True # Return True indicating image found and clicked
else:
print("Image not found in the right half of the screen.")
return False
except pyautogui.ImageNotFoundException:
print("Image not found in the right half of the screen.")
return False
def to_test():
"""Main function to start and stop the loop with F1 and F2."""
print("Press F1 to start the loop and F2 to stop.")
while True:
# Wait for F1 to start the loop
if keyboard.is_pressed('F1'):
print("F1 pressed, starting the loop...")
# Search for the image only once
if to_sample(sample, region):
print("Image found and clicked!")
else:
print("Image not found. Waiting for F1 to start again.")
print("Press F2 to stop.")
while not keyboard.is_pressed('F2'): # Wait until F2 is pressed to stop
time.sleep(0.1) # Wait briefly to avoid CPU overload
print("F2 pressed, stopping the program.")
break # Exit the loop and stop the program
# Wait for F2 to stop the script
if keyboard.is_pressed('F2'):
print("F2 pressed, stopping the program.")
break # Exit the program if F2 is pressed
time.sleep(0.1) # Short delay to prevent high CPU usage
if __name__ == "__main__":
to_test()
[b]Тогда следующий шаг моего кода должен сделать это[/b]
import pyautogui
import time
import keyboard # Import the keyboard library to listen for key presses
import os
# Define image paths
sample1_img = r"C:\Users\sample\Documents\sample\sample1.png"
sample2_img = r"C:\Users\sample\Documents\sample\sample2png"
sample3_img = r"C:\Users\sample\Documents\sample\sample3.png"
sample4_img = r"C:\Users\sample\Documents\sample\sample4.png"
sample5_img = r"C:\Users\sample\Documents\sample5\sample5.png"
sample6_img = r"C:\Users\sample\Documents\sample6\sample6.png"
sample7_img = r"C:\Users\sample\Documents\sample7\sample7.png"
sample8_img = r"C:\Users\sample\Documents\sample8\sample8.png"
sample9_img = r"C:\Users\sample\Documents\sample9\sample9.png"
def find_and_click_buy(image_path, confidence=0.8, retries=3):
"""Finds the image on the screen and clicks it if found, with retry logic."""
attempt = 0
while attempt < retries:
try:
location = pyautogui.locateCenterOnScreen(image_path, confidence=confidence)
if location:
pyautogui.click(location)
return True
else:
print(f"Image '{image_path}' not found, retrying...")
except pyautogui.ImageNotFoundException as e:
print(f"Image '{image_path}' not found on attempt {attempt + 1}.")
attempt += 1
time.sleep(1)
print(f"Failed to find image: {image_path} after {retries} attempts.")
return False
def to_buy():
"""Perform the entire process of buying."""
print("Starting the 'Buy' process.")
# Step 1: Keep searching for "sample1.png"
while True:
sample1_location = pyautogui.locateCenterOnScreen(sample1_img, confidence=0.8)
if sample1_location:
print("Found 'sample1.png', starting purchase process.")
# Step 2: Move cursor 60 pixels down from the center of "sample1.png" and right-click
pyautogui.moveTo(sample1_location.x, sample_location.y + 60)
pyautogui.rightClick()
time.sleep(1)
# Step 3: Look for "sample2.png" and click it
if find_and_click_buy(trade_img):
print("Clicked on 'sample2.png'.")
time.sleep(2)
# Step 4: Look for "sample3.png" and click it
if find_and_click_buy(sample3_img):
print("Clicked on 'sample3.png'.")
# Step 5: Move mouse to the center of the screen and scroll down
pyautogui.moveTo(pyautogui.size().width // 2, pyautogui.size().height // 2)
pyautogui.scroll(-1500)
# Step 6: Look for "sample4.png" while scrolling
if find_and_click_buy(sample4_img):
print("Clicked on 'sample4.png'.")
time.sleep(1)
# Step 7: Look for "sample8.png" and click it
if find_and_click_buy(sample8_img):
print("Clicked on 'sample8.png'.")
# Step 8: Look for "sample9.png" and click it
if find_and_click_buy(sample9_img):
print("Clicked on 'sample9.png'.")
# Step 9: Look for "sample5.png" and click it
if find_and_click_buy(sample5_img):
print("Clicked on 'sample5.png'.")
time.sleep(1)
# Step 10: Look for "sample4.png" and scroll down again while looking for "sample6.png"
if find_and_click_buy(sample4_img):
print("Clicked on 'sample4.png'.")
pyautogui.moveTo(pyautogui.size().width // 2, pyautogui.size().height // 2)
pyautogui.scroll(-1800)
# Step 11: Look for "sample6.png" while scrolling
if find_and_click_buy(_sample6_img, confidence=0.5): # Lower confidence for sample7
print("Clicked on 'sample7.png'.")
time.sleep(1)
# Step 12: Look for "sample8.png" and click it again
if find_and_click_buy(sample8_img):
print("Clicked on 'sample8.png' again.")
# Step 13: Look for "sample9.png" and click it again
if find_and_click_buy(sample9_img):
print("Clicked on 'sample9.png' again.")
time.sleep(1)
break # Exit the loop after completing the sequence
else:
print("Failed to find 'sample9.png' after.")
else:
print("Failed to find 'sample8.png' after")
else:
print("Failed to find 'sample6.png'.")
else:
print("Failed to find 'sample4.png'.")
else:
print("Failed to find 'sample5.png'.")
else:
print("Failed to find 'sample9.png'.")
else:
print("Failed to find 'sample8.png'.")
else:
print("Failed to find 'sample2.png'.")
else:
print("Failed to find 'sample2.png'.")
break # Exit the loop after completing the sequence
else:
print("Looking for 'sample1.png'...") # Keep searching for 'sample1.png' if not found
time.sleep(1) # Wait for 1 second before checking again
def main():
print("Press F1 to start the reagent buying process.")
print("Press F2 to stop the program at any time.")
while True:
# Wait for the user to press F1 to start the process
if keyboard.is_pressed('F1'):
print("F1 pressed, starting 'Buy Reagents' process...")
to_buy()
break # Exit after the process is completed
# Wait for the user to press F2 to stop the script
if keyboard.is_pressed('F2'):
print("F2 pressed, stopping the program.")
break # Exit the loop if F2 is pressed
time.sleep(0.1) # Add a short delay to prevent high CPU usage from constant checking
if __name__ == "__main__":
main()
[b]Тогда это последний шаг:[/b]
import pyautogui
import time
import keyboard # Import the keyboard library to listen for key presses
# Define the image paths
goingapo_img = r"C:\Users\sample\Documents\sample\goingapo.png"
reagentprep_img = r"C:\Users\sample\Documents\sample\reagentpreparation.png" # Updated image name
clock_img = r"C:\Users\sample\Documents\sample\clock.png"
# Get screen size
screen_width, screen_height = pyautogui.size()
# Define the upper-right quadrant region for the "goingapo" image
region = (screen_width // 2, 0, screen_width // 2, screen_height // 2)
def find_and_click_reagent_prep(image_path, offset_y=0, region=None):
"""Locate an image on the screen, click on it, and apply an optional vertical offset."""
try:
# Locate the image on the screen or within a specific region
location = pyautogui.locateCenterOnScreen(image_path, region=region, confidence=0.8)
if location:
print(f"Found image: {image_path} at {location}")
# Calculate the new position with the vertical offset (downwards from the center)
new_x = location.x
new_y = location.y + offset_y
# Move the cursor to the new position and click
pyautogui.moveTo(new_x, new_y)
pyautogui.click()
print(f"Moved cursor to ({new_x}, {new_y}) and clicked.")
return True
else:
print(f"Image not found: {image_path}")
return False
except pyautogui.ImageNotFoundException:
print(f"Image not found: {image_path}")
return False
def main():
"""Main function that starts and stops the loop with F1 and F2."""
print("Press F1 to start the loop and F2 to stop.")
while True:
# Wait for F1 to start the loop
if keyboard.is_pressed('F1'):
print("F1 pressed, starting the loop...")
# Step 1: Look for "goingapo.png" image in the upper-right quadrant and click
if find_and_click_reagent_prep(goingapo_img, region=region):
print("Image 'goingapo.png' found and clicked!")
# Step 2: Wait for 15 seconds before searching for reagentprep_img
print("Waiting for 15 seconds...")
time.sleep(15)
# Step 3: Look for "reagentprep_img.png" and click 40px down from the center
if find_and_click_reagent_prep(reagentprep_img, offset_y=40):
print("Image 'reagentprep_img.png' found and clicked!")
# Step 4: Look for "clock.png" and click
if find_and_click_reagent_prep(clock_img):
print("Image 'clock.png' found and clicked!")
else:
print("Failed to find 'clock.png'.")
else:
print("Failed to find 'reagentprep_img.png'.")
else:
print("Failed to find 'goingapo.png'.")
print("Press F2 to stop.")
# Wait until F2 is pressed to stop the program
while not keyboard.is_pressed('F2'):
time.sleep(0.1) # Wait briefly to avoid CPU overload
print("F2 pressed, stopping the program.")
break # Exit the program after pressing F2
# Wait for F2 to stop the script
if keyboard.is_pressed('F2'):
print("F2 pressed, stopping the program.")
break # Exit the program if F2 is pressed
time.sleep(0.1) # Short delay to prevent high CPU usage
if __name__ == "__main__":
main()
Подробнее здесь: [url]https://stackoverflow.com/questions/79225171/combining-python-scripts-into-one-that-doesnt-affect-their-functions[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия