I need to .Popen a pdf, let my user view it, print it, do whatever they need to do with it, then once it is closed, delete the file. Currently what I tried is this:
def open_file():
try:
subprocess.Popen(file_path, shell=True)
except:
print(exception)
finally:
if os.path.exists(file_path):
os.remove(file_path)
print("File successfully removed.")
What I need is something more like this:
def open_file():
try:
subprocess.Popen(file_path, shell=True)
except:
print(exception)
finally:
if os.path.exists(file_path):
while file_path.IS_OPEN:
sleep(1)
if file_path.IS_NOT_OPEN:
os.remove(file_path)
print("File successfully removed.")
or something like that. I'm still a novice, so I'm sure my syntax is wrong. Is this possible?
I have found that if I put a sleep function before the os.remove of the first example, I get an error back saying it cannot delete an open file, whereas otherwise it somehow deletes before opening causing the open to error. Can I make some sort of loop based on this first error that keeps checking if a file is open and when it is not, remove it?
Although you open the PDF reader, you don't wait for it to complete. You could wait until the program exits to try the delete. Several subprocess
functions do this, but run
is considering the modern way.
subprocess.run(file_path, shell=True)
This works if the subprocess is in fact the PDF reader. Sometimes an intermediate program runs the reader and then exits, spoiling this solution.