I'm a bit of a noob, so sorry in advance if I'm not doing this right.
I'm using python 3.6x
What I have so far that gets the command window open is
import os
os.open("start cmd")
but this comes up in the directory that I'm working from and not in administration mode.
I've also tried
import os
os.system("start /wait cmd /wait {tskill dwm}")
but that didn't work either. (tskill dwm is what I'm trying to get python to write in to command manager to fix a bug with windows' buttons not going away)
My overall goal is to just click this python script Blah.py and have it restart the windows viewer or whatever it's called. Doing this clears the stuck buttons. Overall this is just an exercise in practicing python. I know I could just disable the button fade out and that would take care of the issue. I just figured this would be a good learning opportunity.
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
keyboard.press(Key.cmd)
keyboard.release(Key.cmd)
time.sleep(0.3)
keyboard.type("cmd")
time.sleep(1)
keyboard.press(Key.right)
keyboard.release(Key.right)
keyboard.press(Key.down)
keyboard.release(Key.down)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(0.5)
keyboard.press(Key.tab)
keyboard.release(Key.tab)
keyboard.press(Key.tab)
keyboard.release(Key.tab)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
exit
The answer is here
https://stackoverflow.com/a/11746382/7352806
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
Related
I made a simple program that works as a .py file, but when I use pyinstaller to make a .exe file, the command prompt opens and closes immediately. By screen recording opening the .exe, I was able to see the following error flash on the command prompt before it closed: "Failed to execute script "kahoot_spammer" due to unhandled exception!"
I am using pyinstaller --onefile kahoot_spammer.py to convert my .py to a .exe file. Here is the code in my program; which I plan on using at school to add a ton of users to the class Kahoot game:
from pynput.mouse import Button, Controller as mController
from pynput.keyboard import Key, Controller as kController
import time
mouse = mController()
keyboard = kController()
#ask user for the kahoot game pin, what name they want the fake players to have, and how many players to create
game_code = input("Game Code: ")
username = input("Username: ")
amount = input("Player Amount: ")
#delay the program so the user can switch to their browser with kahoot open
time.sleep(5)
#create players
for i in range(amount):
#enter game pin
mouse.position = (775, 500)
mouse.click(Button.left, 1)
keyboard.type(game_code)
mouse.position = (775, 550)
mouse.click(Button.left, 1)
time.sleep(0.5)
#enter username
mouse.position = (775, 520)
mouse.click(Button.left, 1)
keyboard.type(username + str(i))
mouse.position = (775, 570)
mouse.click(Button.left, 1)
time.sleep(0.2)
#open new tab with kahoot ready to go
keyboard.press(Key.ctrl)
keyboard.press("t")
keyboard.release(Key.ctrl)
keyboard.release("t")
keyboard.type("https://kahoot.it")
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(1)
Does anyone know how I can fix this error, and have the program run as it should? The .pyc file that is created alongside the .exe works as it should; the command prompt stays open and the program functions as expected.
I would suggest using pyinstaller --onefile --debug=all kahoot_spammer.py to get more debug information.
In my specific case my application failed when importing a logging object associated with my GUI library Kivy. So I commented out the line in my code that turned logging off and it works now.
This link helped me: https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html
I have a little problem with understand what is going on with my code.
I have a lot of lines in my code so i decided to simulate my problem with shorter version.
Im using raspberry pi 4, flirone on rapsbian.
import sys
import os
import time
import subprocess
global shellscript
#global pid
def subprocess_settings():
shellscript = subprocess.Popen(["/home/pi/Desktop/init_flir.sh"], close_fds=True)
#shellscript = subprocess.Popen(["/home/pi/Desktop/init_flir.sh", "&> /dev/null"], stdin=None, stdout=None, close_fds=True)
#pid = shellscript.pid
try:
x = 1
while True:
if x == 0:
sys.exit()
elif x == 1:
print("Yas, x=1")
time.sleep(2)
subprocess_settings()
time.sleep(5)
print("Driver test is in background mode")
time.sleep(2)
print("Close process")
subprocess.Popen.kill(shellscript)
x=0
except KeyboardInterrupt:
subprocess.Popen.kill(shellscript)
and my .sh file:
#!/bin/bash
cd /home/pi/github/flirone-v4l2
sudo modprobe v4l2loopback exclusive_caps=0,0 video_nr=1,2,3
sudo ./flirone ~/github/flirone-v4l2/palettes/Iron2.raw
I want to run my .sh file. It has to work in background. I need to terminate this with 2 ways, first one from keyboard and second inside my elif.
At the end i need to hide terminal output from .sh file.
What im doing wrong??
Is this is a problem with global variables?
How to fix this to work properly?
Thanks for any help.
This solution works properly, as i wanted. In flirone driver i runned ./flirone and opened 1 process from subprocess.Popen and 2 additional processes in flirone code. I checked this running command sudo ./flirone ~/github/flirone-v4l2/palettes/Iron2.raw and ps aux | grep flirone . I used pidof flirone command to check main ID. When im killing this process everything works as should be and other processes ends too.
import sys
import os
import signal
import time
import subprocess
def subprocess_kill():
pidof = subprocess.check_output("pidof flirone", shell=True)
time.sleep(1)
subprocess.check_output("sudo kill -9 %s " % (pidof), shell=True)
try:
x = 1
while True:
if x == 0:
sys.exit()
elif x == 1:
print("x=1")
time.sleep(2)
os.chdir("/home/pi/github/flirone-v4l2")
shellscript = subprocess.Popen("sudo modprobe v4l2loopback exclusive_caps=0,0 video_nr=1,2,3", shell=True)
shellscript2 = subprocess.Popen("sudo ./flirone ~/github/flirone-v4l2/palettes/Iron2.raw", shell=True)
time.sleep(5)
print("Driver test is in background mode")
time.sleep(2)
print("Close process")
subprocess_kill()
x=0
except KeyboardInterrupt:
print("hey")
When i deleted killing method from except KeyboardInterrupt processes ends too.
If you want to hide output of subprocess u can use:
FNULL = open(os.devnull, "w")
shellscript2 = subprocess.Popen("sudo ./flirone ~/github/flirone-v4l2/palettes/Iron2.raw", shell=True, stdout=FNULL)
More: How to hide output of subprocess in Python 2.7
Subprocess python 2.7 lib
My project is to make a program that you can run while you are playing games or other programs in the background.
When you press a certain key, your notepad should open and also close after you press the same key again.
I have managed to open notepad with subprocess and that works fine but I have no idea to make it open only when a certain key is pressed.
Thanks for any help!
EDIT:
What I tried already:
import subprocess
import keyboard
if keyboard.is_pressed('k'):
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
input()
here it just doesn't detect any keyboard input, the input() at the end makes the program not close instantly
import subprocess
import keyboard
keyboard.add_hotkey('ctrl+k', print,args=("hello", "test"))
input()
Here if I press "ctrl+k it" will print hello test that means the hotkey works fine. When I switch this part "print,args=("hello", "test")" to "subprocess.Popen('C:\Windows\System32\notepad.exe')"(it should open the program instead of printing hello test) the notepad opens instantly after I run the program and when I press "ctrl+k" I get a big error.
A more complex, but still working example could be the following. With this code your program will be always listening the keyboard, not only when you are focused on the input, so may be mre practical in your case
from pynput import keyboard
import subprocess
import threading
class MyException(Exception): pass
class Listening:
"""Is allways waiting for the keyboard input"""
def __init__(self):
self.notepad_open = False # to know the state
with keyboard.Listener(
on_press=self.on_press) as listener:
try:
listener.join()
except:
pass
def on_press(self, key):
try:
if key.char == "k":
if not self.notepad_open:
self.subprocess = \
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
self.notepad_open = True # update state
else:
self.subprocess.kill()
self.notepad_open = False # update state
except: # special key was pressed
pass
thread = threading.Thread(target=lambda: Listening())
thread.start()
The problem is that you check for the key 'k' only once at the beginning. If you want the program to correctly work then you should try this:
import time
import subprocess
import keyboard
while True:
if keyboard.is_pressed('k'):
subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
time.sleep(5)
-I used the time so that you can only open the program once 5 seconds(If you're curious, see what happens without it)-
I took a piece of code from here:
https://stackoverflow.com/a/10457565/13882705
which is
# I have used os comands for a while
# this program will try to close a firefox window every ten secounds
import os
import time
# creating a forever loop
while 1 :
os.system("TASKKILL /F /IM firefox.exe")
time.sleep(10)
It will terminate a process if it is running using OS module
But if the program did not find the app we mentioned then it prints
ERROR: The process "firefox.exe" not found.
Is there a way to make the program just print application not found once and wait until the program is rerunned?
It is fine even if it just prints "Application Not found"
Use subprocess.run instead of os.system so you have more control:
import subprocess
import time
while True:
proc = subprocess.run(["TASKKILL", "/F", "/IM", "firefox.exe"], stderr=subprocess.PIPE)
if proc.returncode != 0:
print("Application not found.")
break # since application isn't here we just exit
time.sleep(10)
I have tried each of these solutions to no avail in attempt to achieve the same thing that was discussed on this thread. Yet that console window sticks around.
#kill console through .system
import os, sys
#webbrowsing modules
from selenium import webdriver
#function to launch browser in chrome
def launch_chrome(page):
browser = webdriver.Chrome(r'C:\Users\cj9250\AppData\Local\Continuum\anaconda3\chromedriver.exe')
browser.get(page)
return browser
url = "https://www.google.com/"
browser = launch_chrome(url)
#prints 'SUCCESS: The process "chromedriver.exe" with PID 9872 has been terminated.'
#in the terminal and leaves it open
os.system('taskkill /F /im chromedriver.exe')
quit()
#never gets to this print command
print('it quit')
#closes the browser as well
browser.service.stop()
sys.exit
print('it exit')
I should note that I am running my programs from batch files called by win+r similar to the way described in Automate the Boring Stuff. I also am running Python through Anaconda.