How Do I Launch A File In Its Default Program, And Then Close It When The Script Finishes?
Solution 1:
The problem lies within the fact, that the process being handled by the Popen
class in your case is the start
shell command process, which terminates just after it runs the application associated with given file type. The solution is to use the /WAIT
flag for the start
command, so the start
process waits for its child to terminate. Then, using for example the psutil
module you can achieve what you want with the following sequence:
>>>import psutil>>>import subprocess>>>doc = subprocess.Popen(["start", "/WAIT", "file.pdf"], shell=True)>>>doc.poll()>>>psutil.Process(doc.pid).get_children()[0].kill()>>>doc.poll()
0
>>>
After the third line Adobe Reader appears with the file opened. poll
returns None
as long as the window is open thanks to the /WAIT
flag. After killing start
's child Adobe Reader window disappears.
Other probably possible solution would be to find the application associated with given file type in the registry and run it without using start
and shell=True
.
I've tested this on 32 bit Python 2.7.5 on 64 bit Windows Vista, and 32 bit Python 2.7.2 on 64 bit Windows 7. Below is an example run on the latter. I've made some simple adjustments to your code - marked with a freehand red circles (!).
Also, possibly it is worth to consider this comment from the documentation:
The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.
and run the process as follows:
subprocess.Popen("start /WAIT " + self.file, shell=True)
Post a Comment for "How Do I Launch A File In Its Default Program, And Then Close It When The Script Finishes?"