I've working on a windows python program and I need it to run once I open an app. Is it possible ? If so how would I implement it ?
Asked
Active
Viewed 280 times
2 Answers
1
We need some information, what did you want to do? Did you wanna know, if a process is started and then you will continue you python script? Than you can do this:
import psutil
def is_process_running(processName):
for process in psutil.process_iter(): # iterates through all processes from your OS
try:
if processName.lower() in process.name().lower(): # lowers the name, because "programm" != proGramm"
return True # if the process is found, then return true
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): # some failures what could go wrong
pass
return False;
while(!is_process_running('nameOfTheProcess') # only continue as long as the return is False
time.sleep(10) # wait 10 seconds
For further information: psutil-docs

robni
- 904
- 2
- 6
- 20
-
could you specify how this code works so I can better incorporate it into my script – Jun 22 '22 at 11:19
-
I comment the code. Could you read it now? – robni Jun 22 '22 at 11:27
-
yes it's much easier to understand now – Jun 22 '22 at 11:32
1
This can be achieved in multiple ways, following can also be the one.
import subprocess
#sub-process library being part of python doesn't
#require any additional installation and can do all the work.
#For Windows operating system we can use 'tasklist'
#in place of 'ps aux' as the first argument
#(haven't work with windows lately but this is close to something i remember).
#check_output api called when shell=true,returns list of running processes.
running_processes = subprocess.check_output(['ps aux'], shell=True)
#check if the application needed is running, for brevity, I am using firefox,
#if yes, it fires off another python script.
if bytes('firefox',encoding='utf-8') in running_processes:
subprocess.call(['python3', '/path/to/application.py'])
else:
print('it not')

dashkandhar
- 83
- 1
- 7

Ajackus
- 11
- 2