How do I launch a file in its default program, and then close it when the script finishes?

前端 未结 1 814
你的背包
你的背包 2020-12-15 23:31

Summary

I have wxPython GUI which allows the user to open files to view. Currently I do this with os.startfile(). However, I\'ve come

相关标签:
1条回答
  • 2020-12-16 00:07

    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 (!).

    step1 step2 step3 step4

    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)
    
    0 讨论(0)
提交回复
热议问题