Close console but leave selenium browser open - python

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.

Related

Run a webbrowser and continue script without close the browser

I need help with this code:
import webbrowser
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open('https://www.google.com/')
print('test browser')
it open chrome and visit the website, but don't print until I close the browser.
If I use this one:
import webbrowser
webbrowser.open('https://www.google.com/')
print('test browser')
It run default browser(brave), visit the website and print correctly.
How can I run X browser and print without need of close it to continue script?
You could create a new Thread and in that thread open the browser:
from threading import Timer
def open_browser():
webbrowser.open('https://www.google.com/')
Timer(1, open_browser).start()
print(“test”)
Everything that has to do with interaction of the browser should now be placed in def open_browser():
This code will set a timer for 1 millisecond and then execute the function within a seperate thread, so your code keeps executing.

Unable to prevent program to print a Error

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)

Python Chromedriver End Task Annoying Flicker

I am building a Tkinter app with python that initializes multiple selenium webdrivers. The initial problem was that lots of chromedriver.exe instances were filling up user's memory, even after using driver.quit() (sometimes). So to get rid of this issue, when closing the tkinter app, I wrote this line os.system("taskkill /f /im chromedriver.exe /T"), that solves my problem, but, by using this, a command prompt instance is initiated that self kills almost instantly. The problem is that the user can see it and I find it kinda disturbing. Is there any way I could hide it? Or is there a workaround for my initial problem, that is user friendly?
Use both driver.close() and driver.quit() in your code in order to free memory.
driver.close()
driver.quit()
To reduce the memory footprint you should use ChromeDriver-Service:
First you start the service, then use it when creating new drivers, and finally stop the service before program exit.
Put the code below in chrome_factory.py and then:
on program start call chrome_factory.start_service()
to create new driver call chrome_factory.create_driver()
the service and drivers will be automatically stopped/quit at program exit.
Using this approach will result in only ever having single chromedriver.exe process.
# chrome_factory.py
import atexit
from os.path import expanduser
from typing import Optional
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
EXECUTABLE = expanduser("~/bin/chromedriver")
_chrome_service: Optional[Service] = None
def start_service():
global _chrome_service
_chrome_service = Service(EXECUTABLE)
_chrome_service.start()
atexit.register(_chrome_service.stop)
def create_driver() -> webdriver.Remote:
global _chrome_service
opts = webdriver.ChromeOptions()
opts.add_argument("--headless")
driver = webdriver.Remote(_chrome_service.service_url,
desired_capabilities=opts.to_capabilities())
atexit.register(driver.quit)
return driver
def main():
start_service()
for _ in range(20):
create_driver()
if __name__ == '__main__':
main()

Python wait for subprocess to finish before terminating

I am developing a python script that opens a program using the subprocess module and then using the pyautogui module to send keyboard shortcuts to the program. However, when the program opens and I send the CTRL + O shortcut to it, the program opens a file and then does some processing on that file.
Is there a way, using the subprocess module in python to wait until the program has finished processing (but is still running) to then input the CTRL + S shortcut (using pyautogui) before finally terminating the program/process?
Here is a sample of the code I'm using:
from pyautogui import press, typewrite, hotkey, moveTo
from subprocess import Popen, PIPE, STDOUT
import time
import os
def saveNClose(program, out_filename):
# open the save file dialog
hotkey('ctrl', 's')
#wait for save file dialog to appear
time.sleep(0.5)
# enter the file path of the file to save
typewrite(out_filename, interval=0.01)
# save to file
press('enter')
#close kurzweil
program.terminate()
def openProgram(in_fname, out_fname, wait_time):
#open kurzweil
program = Popen([r"C:\Program Files (x86)\Kurzweil Educational
Systems\Kurzweil 3000\Kurzweil 3000.exe"], stdout=PIPE, stdin=PIPE,
stderr=STDOUT, shell=False)
#wait for login screen to appear
time.sleep(2)
#login with creditentials Here
press('enter') #login
#wait for kuzweil to load
time.sleep(8)
#open the open file dialog
hotkey('ctrl', 'o')
#wait for open file dialog to appear
time.sleep(1)
#enter the file path of the file to open
typewrite(in_fname, interval=0.01)
#open the file
press('enter')
#wait for the conversion options to appear
time.sleep(0.5)
# confirm conversion options
press('enter')
# Program Does Processing Here
#**************************************************
# Need help Here to wait until processing is done.
#**************************************************
#Then input CTRL + S and Terminate.
saveNClose(program, out_fname)

How to open command prompt in Administrator mode in python?

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)

Categories

Resources