4

I can open a PDF file from within Python using subprocess.Popen() but I am having trouble closing the PDF file. How can I close an open PDF file using Python. My code is:

# open the PDF file
plot = subprocess.Popen('open %s' % filename, shell=True)

# user inputs a comment (will subsequently be saved in a file)
comment = raw_input('COMMENT: ')

# close the PDF file
#psutil.Process(plot.pid).get_children()[0].kill()
plot.kill()

Edit: I can close the PDF immediately after opening it (using plot.kill()) but this does not work if there is another command between opening the PDF and 'killing' it. Any help would be great - thanks in advance.

gpce
  • 83
  • 1
  • 7
  • https://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true – Ewoud Jan 21 '17 at 23:25
  • @Ewoud thanks for the pointer. I tested those examples to close my PDF file but the PDF file remains open. Do you have any ideas? – gpce Jan 21 '17 at 23:45

1 Answers1

-1

For me, this one works fine (inspired by this). Perhaps, instead of using 'open,' you can use a direct command for the PDF reader? Commands like 'open' tend to make a new process and then shut down immediately. I don't know your environment or anything, but for me, on Linux, this worked:

import subprocess
import signal
import os

filename="test.pdf"
plot = subprocess.Popen("evince '%s'" % filename, stdout=subprocess.PIPE,
                    shell=True, preexec_fn=os.setsid)

input("test")
os.killpg(os.getpgid(plot.pid), signal.SIGTERM)

On windows/mac, this will probably work if you change 'evince' to the path of the executable of your pdf reader.

David Beauchemin
  • 231
  • 1
  • 2
  • 12
Ewoud
  • 741
  • 4
  • 6