Ekaterina Mishina
Ekaterina Mishina

Reputation: 1723

Close pdf-file or exe-application from Python

  1. My application is opening a pdf-file with os.startfile on user's request (push button). Is there any way to close this pdf when user pushes the button another time? If this is not done, I get the error:

    WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'default_report.pdf'

    Edit: Within Python I get: QPainter::begin(): Returned false (WindowsError comes from executable). Can I catch this err somehow with try? At least to ask user to close the pdf manually...

  2. Another related question. My application is compiled as an executable and is called from another, VB6, application (also on push button). Is there any way to detect that executable is already running (exe-file always has the same location) from Python and kill it in this case prior to starting it again? Problem is similar, I get the error if I run the executable second time because they start to conflict (they use common db). From VB6 it doesn't work somehow, I don't know details...

    Edit: solved with psutil (see my comment to the answer by jheyse)

p.s. I use Python 3.2, PyQt 4 and cx_freeze for exe production if it matters.

Upvotes: 2

Views: 3237

Answers (1)

jheyse
jheyse

Reputation: 489

1.I don't think it's directy possible because as the docs say "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."

2.To kill a process by name from python you can use the psutil module. Something like this (the following code will kill windows calculator if it is open):

for p in psutil.process_iter():
    if p.name == 'calc.exe':
        p.kill()

Upvotes: 2

Related Questions