使用 python 中的子进程关闭 pdf

Close pdf using subprocess in python

我尝试关闭通过以下过程打开的 pdf:

import subprocess
openpdffile = subprocess.Popen([file_path], shell=True)    

我试过了

openpdffile.kill()

但这使 pdf 在我的 pdf 中保持打开状态 reader。有什么建议吗?

非常感谢。

原因是subprocess.Popen创建了一个新进程。因此,您的代码中究竟发生了什么,您正在创建一个新流程,然后您正在关闭该 new 流程。相反,您需要找出进程 ID 并杀死它。

注意:shell 命令在 Windows 系统上工作。要在 UNIX 环境中使用它们,您需要更改 shell 命令

import os
import subprocess

pid = subprocess.getoutput('tasklist | grep Notepad.exe').split()[1]
# we are taking [1] because this is the output produced by 
# 'tasklist | grep Notepad.exe'
# Image Name PID  Session Name  Session Mem Usage
# ========== ==== ============= ======= =========
# Notepad.exe 10936 Console 17  16,584 K
os.system(f'taskkill /pid {pid}')

编辑:要终止特定进程,请使用以下代码

import os
import subprocess

FILE_NAME = 'test.pdf' # Change this to your pdf file and it should work

proc = subprocess.getoutput('tasklist /fi "imagename eq Acrobat.exe" /fo csv /v /nh')
proc_list = proc.replace('"', '').split('\n')
for x in proc_list:
    p = x.split(',')
    if p[9].startswith(FILE_NAME):
        pid = p[1]
        os.system(f'taskkill /pid {pid}')

你可以在完成子进程的事情后得到pid,并决定为了你的方便而杀死哪个。

在这里您可以学习如何获取子进程的 pid: