This is part of a python program under windows environment. I am trying to do the following:
from an html, I want to create a pdf and then open it:
#create the pdf
os.system("start wkhtmltopdf.exe result.html %s%s" %(output_directory, pdf_document_name))
#open the current pdf
os.system("start %s%s" %(output_directory, pdf_document_name))
The issue is that sometimes the script of creating the pdf is slower, so I get an error from the terminal saying that there is no file with such name.
I want to ask whether it’s possible to call the pdf open only when the creation is successful and finished. I know how to do it by invoking a time.sleep() , but I think that’s not too professional.
Many thanks,
D
Regardless of the method you use to execute shell commands (subprocess, os.system, etc.), you should verify that your file exists before trying to open it. You can then instrument the delay into the File-Exists-Else-Wait-Repeat loop before trying to open it.
You can do this using os.path.exists():
The other thing to look at is that this introduces a security vulnerability, as the file could change in the time that passed between your verifying it and opening it (e.g. it could have been replaced with malicious code).
Another way to handle this is to try to open it within a try… except… block, but this doesn’t really resolve the security issue (the file could have been replaced between creation and your attempt at opening it anyway).