Python wait for subprocess to finish before terminating - python

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)

Related

How do I open a program in the background and exit the script with no output text?

For example, if I run Popen(["firefox", "https://example.org/"]), I get a message along the lines of
Gtk-Message: 21:33:04.621: Failed to load module "appmenu-gtk-module"
Is there a way to run that same Popen (or any equivalent) and have no messages printed to the screen, and then kill the program (main.py)?
Eg:
command(["firefox", "https://example.org/"])
exit(0)
Opens firefox, then automatically exits the program, leaving the command() still active, and with no output from command().
you just have to start a new detached session and null stderr and stdout
from subprocess import Popen
import subprocess
import os
process = Popen(["firefox", "https://example.org/"],
stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
start_new_session=True)
exit(0)

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.

Python execute command in console

I'm trying to make a program that takes a command and executes it in the console of any operating system and prints the response in python. For this I'm using subprocess.check_output. The program works fine with the ipconfig command (I'm on windows), and the response gets printed after no time. With the notepad command, it opens notepad and only continues when I close notepad. Is it possible to just continue without notepad being closed?
Code:
import subprocess
def executeCommand(command):
return subprocess.check_output(command).decode('ISO-8859-1')
def cmdCommand(command):
pool = ThreadPool(processes=1)
asynch_result = pool.apply_async(executeCommand, [command])
for i in range(3):
if asynch_result.get() is not None:
return asynch_result.get()
sleep(1)
pool.terminate()
return "No result gotten"
print(cmdCommand("ipconfig"))
print(cmdCommand("notepad"))

subprocess.Popen() a python file with an infinite loop never calls the file

I have two .py files on a Raspberry Pi where I am trying to call one file, keep_awake.py, which contains:
import time
import serial
while True:
time.sleep(5)
for option in ["on", "off"]:
for board in ["ACM0", "ACM1"]:
request = serial.Serial(f"/dev/tty{board}", 19200, timeout=1)
for j in [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"]:
request.write(f"relay {option} {j}\r".encode("utf-8"))
request.close()
time.sleep(.1)
This code is writing to relays to click buttons via wires soldered into the circuit boards. I have tested this code and know that it works. However, when I call it from the parent file like this
subprocess = Popen(["python", "/home/pi/Desktop/DLMW-ART/tools/keep_awake.py"], stdout=PIPE, stderr=STDOUT, universal_newlines=True)
The code does not run.
The purpose of this is to push the devices button so that it stays awake during a firmware update, and then kill the subprocess so it doesn't interfere with the rest of the script. So I want the parent file to look like this:
#Several print statements to let me know where in the script I am
subprocess = Popen(["python", "/home/pi/Desktop/DLMW-ART/tools/keep_awake.py"], stdout=PIPE, stderr=STDOUT, universal_newlines=True)
#Firmware update code will live here
time.sleep(20) #used for testing the call
subprocess.kill()
This code runs in a loop, so I can clearly see the multiple print statements in the main file, but nothing happens in the subprocess, and the devices are not clicked. Am I making the subprocess.Popen call incorrectly?

Close console but leave selenium browser open

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.

Categories

Resources