I have this code:
import pyautogui
import subprocess
# iniciate the program
subprocess.call(['C:\Program Files (x86)\someprogram\someprogram.exe'])
# Abrir folder
pyautogui.moveTo(110, 54, duration=1)
pyautogui.click(clicks=1, interval=1, button='left')
but the mouse wont move it the program initiates from new, it only moves it the exec is already open, what could it be?
Its most likely a permission's issue. Have you tried running the program as an admin?
Related
I have a .py file that runs via Task Scheduler when I log into my computer, and it's constantly listening for specific keyboard events to happen. Rather than having it run in the Python Console window on the Taskbar, I'd like to get it to run in the system tray with a Python icon to make it more clean.
I have discovered the pysystray library, and can successfully make a Python icon in the system tray with a right-click menu which will allow me to quit the icon.
from os import path as path
import PIL.Image
import pystray
def on_clicked(icon, item):
if str(item) == "Quit":
icon.stop()
dir_path = path.dirname(path.realpath(__file__))
icon_image = "\\Icon\\Python.ico"
full_path = dir_path + icon_image
image = PIL.Image.open(full_path)
icon = pystray.Icon(
"Testing",
image,
menu=pystray.Menu(pystray.MenuItem("Quit", on_clicked)),
)
icon.run()
However, I can't figure out how to get my existing Python file to run under the icon. It seems like there are two separate events happening; one for launching the icon, and another for running the rest of the code. I would want to make sure that if the "Quit" option is chosen, then the .py file would also stop.
Also, it would be really helpful to have a separate right-click menu item which will display either Python cmd line text since it's constantly being overwritten in my main .py file with a print statement.
Any help/insight would be really appreciated!
The pystray.run function accepts an optional callback function as a parameter. The callback function is run in a separate thread and should be closed normally by ln 9: icon.stop().
I'm looking for a way to execute a spacebar click within a fullscreen game whenever a certain image appears.
My problem is that out of the game the code works perfectly, but when I run the game and leave it on screen the script doesn't work.
I searched for some solutions with a "pydirectinput" library, but the problem persists.
I'm new to Python and I don't know exactly how to get around this.
from turtle import width
from pyautogui import *
import pyautogui
import pydirectinput
while True:
if pyautogui.locateOnScreen('barra.png', region=(700, 700, 500, 500), confidence=0.8) != None:
print("Press backspace!")
pydirectinput.press('space')
I'm learning python with the book python crash course , i wrote the code for the game alien invasion , but it is not working , when i write "import sys" , the word sys is underscore and the program opens up the screen for like a millisecond and then it closes itself, i look for an answer in this site and YouTube and i haven't been able to find a solution, can anyone help? thanks in advance.
I'm using vs code on Linux mint.
this is what i wrote so far:
from settings import Settings
from ship import Ship
import sys
class AlienInvasion:
"""overall class to manage game assets and behavior"""
def __init__(self):
""" initialize the game and creates game resources"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode(
(self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
"""start the main loop for the game."""
while True:
self._check_events()
#whatch for keyboard and mouse events .
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
#redraw the screen during each pass through the loop.
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
#make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
#make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
It looks like there's probably an error being thrown somewhere in your script that is causing the program to stop running, and as such, close the terminal as soon as it is opened. In my experience, this only happens when you execute the script from a file browser UI by double-clicking it.
To fix this, try running the program from somewhere that will stay open, even when the program is terminated, like, for example, the built-in terminal in vscode (you can reveal by going to view > terminal). To run the program, then simply run the command:
python path/to/my/script.py
If it causes an error, you will then be able to see it printed nicely, without the terminal closing.
On another note, importing sys has nothing to do with this problem. The reason it is highlighted by pylance is that you have imported it, but then you haven't used it anywhere (for example calling a function like sys.exit()), so it thinks that the line is unnecessary. It will go away once you use the sys module somewhere else in the script.
According to your error content, I think this is caused by the fact that the file is not found, meanwhile sys is not used in your code.
Here are some reasons caused "FileNotFoundError", you could confirm one by one:
1. File name and file type
The wrong file name was inserted into the code. Please carefully check the document name.
2. Escape of Python string
In the string of file, the address string information similar to C:\user\desktop will be involved, which conflicts with the escape function in Python string, such as \n representing line feed. Use r"C:\User\Desktop" or C:\\User\\Desktop to avoid Python escaping strings.
3. Relative path problem
Generally, it is not recommended to use. In the process of Python running, the relative path is the folder that the process points to when running, and the folder is used as the file tree of the root node, that is, if you open the file by using the relative path, you can only access the file under its root node.
You could use the methods os.path.abspath() and os.path.abspath('..') provided in the OS library to view and change the absolute path where Python runs.
4. Python runtime location
If it is such a problem, you can add the following code to the head of the file:
import sys
sys.path.append("../your/target/path/")
try pip install os-sys and pip install syspath
enter link description here
I need to run a code for hours, and the computer I am working with has a (forced and unchangeable) screensaver policy. (It locks after 10 minutes). What can I do to prevent it? Is there any line of code to prevent that?
This worked for me. I'll just leave it here so people can use it.
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002) #this will prevent the screen saver or sleep.
## your code and operations
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000) #set the setting back to normal
You can prevent screen saver by moving mouse cursor on a fixed period of time, below function can handle cursor moving.
import win32api
import random
def wakeup():
win32api.SetCursorPos((random.choice(range(100)),random.choice(range(100))))
This is a coded solution that you can place in your program (also works for Mac users):
pip3 install pyautogui
https://pypi.org/project/PyAutoGUI/ (Reference)
import pyautogui
import time
def mouse_move():
while True:
pyautogui.moveTo(100, 100, duration = 1) # move the mouse
time.sleep(60) # Every 1 min
pyautogui.moveTo(50, 100, duration = 1) # move the mouse
mouse_move()
Or, without the while loop, run it when required if your program is already within a while loop:
def mouse_move():
pyautogui.moveTo(50, 100, duration = 1) # move the mouse
mouse_move()
Just a quick question: In a game, I'm making, I want the player to be able to pick an audio file from his/her computer and play it in the game and I'm not all that sure how to do it. I want them to be able to open a browse files screen (default file explorer) and then select a music file and play it as bgm, all by the click of a button.
Now I know Tkinter doesn't support sound but I don't care how the program runs. As long as I can fit it into my code. If you need my code, it's here: https://github.com/SeaPuppy2006/FruitClicker (I'm using my windows build at the moment). Thanks!
You could use playsound module and use a thread to prevent block:
from playsound import playsound
import tkinter
from tkinter import filedialog
import threading
def f():
def play():
pathname = filedialog.askopenfilename()
playsound(pathname)
threading.Thread(target=play).start()
root = tkinter.Tk()
tkinter.Button(root,text="playsound",command=f).grid()
root.mainloop()