Home > OS >  Is there any way to delay a Python Script till an Application is running?
Is there any way to delay a Python Script till an Application is running?

Time:10-17

I want the Python Code to open Notepad and let the user type in it, by the time it should not execute the rest of the code. After I close notepad, it should resume the script from where it left. Is there any way to do this? Or should I try a different approach?

What have I Tried:

  • Here is the code so far -
with open('file.txt','w') as file: #this is to create an empty file
    file.close()
    pass
os.startfile('file.txt')
time.sleep() # what value should I enter for time.sleep? or is there a module to do this?
  • I possibly can run a while loop to check whether the notepad.exe is running or not, if it is, if it's not, it should break out of the loop and execute the rest of the code.
    However, the problem is how do I check if notepad.exe is running?

  • Running a while loop to delete the file, if it get's an error, means the program is still running, but the problem is if it does not get the error, It will delete the file.

It would be better, if when launching of the program, it takes the process ID of it, and only wait for it to terminated. So that other instances of notepad won't be affected.

CodePudding user response:

From the docs:

startfile() returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status.

If you know the path of the application to open the file with, you could use subprocess.Popen() which allows for you to wait.

p = subprocess.Popen([
    'C:\\Windows\\System32\\notepad.exe', 
    'path\\to\\file'
])

(output, err) = p.communicate()  

#This makes the wait possible
p_status = p.wait()

See: http://docs.python.org/library/os.html#os.startfile

http://docs.python.org/library/subprocess.html#subprocess.Popen

  • Related