如果使用打开文件,如何知道文件是否已关闭子流程。Popen?

2024-09-30 01:18:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中使用以下命令打开文件:

file = os.path.normpath(file_path)
phandler = subprocess.Popen(['open', '-W', file])

我在投票

^{pr2}$

查看进程是否已终止。如果进程是用cmd+Q终止的,它是有效的。但是,如果我用cmd+w关闭文件,这是不起作用的。有什么万无一失的方法来确保文件不再打开。在

从phandler,我也可以使用幻影器pid如果需要的话。在

如果没有其他方法可以做到这一点,我可能不得不使用像watchdog这样的库,它是iNotify的包装器,但是如果我可以使用像psutils这样的库来实现这一点,那就更好了。在


Tags: 文件path方法命令cmd进程osopen
1条回答
网友
1楼 · 发布于 2024-09-30 01:18:58

你要找的是这样的东西:

from __future__ import print_function  # If in Python 2.x, import print function from Python 3.x

import os
import subprocess
import time

import psutil

def get_proc_status(pid):
    """Get the status of the process which has the specified process id."""

    proc_status = None
    try:
        proc_status = psutil.Process(pid).status()
    except psutil.NoSuchProcess as no_proc_exc:
        print(no_proc_exc)
    except psutil.ZombieProcess as zombie_proc_exc:  
        # For Python 3.0+ in Linux (and MacOS?).
        print(zombie_proc_exc)
    return proc_status

def open_file(app, file_path):
    """Open the specified file with the specified app, and wait for the file to be closed. """

    my_file = os.path.normpath(file_path)
    # phandler = subprocess.Popen(['open', '-W', my_file])
    # Must be for Macs. Doesn't work in Windows or Linux.
    phandler = subprocess.Popen([app, my_file])
    pid = phandler.pid

    pstatus = get_proc_status(pid)
    while pstatus is not None and pstatus != "zombie":
        # The allowed set of statuses might differ on your system.
        print("subprocess %s, current process status: %s." % (pid, pstatus))
        time.sleep(1)  # Wait 1 second.
        pstatus = get_proc_status(pid)
        # Get process status to check in 'while' clause at start of next loop iteration.

    if os.name == 'posix' and pstatus == "zombie":   # Handle zombie processes in Linux (and MacOS?).
        print("subprocess %s, near-final process status: %s." % (pid, pstatus))
        phandler.communicate()

    pstatus = get_proc_status(pid)
    print("subprocess %s, final process status: %s.\n" % (pid, pstatus))

open_file(r"Evince\bin\Evince.exe", "fuzzed_file.pdf")
open_file(r"Evince\bin\Evince.exe", "unfuzzed_file.pdf")

根据Python:Non-Blocking + Non defunct processhow to kill (or avoid) zombie processes with subprocess module,似乎需要communicate()调用来处理Linux中的“僵尸”进程(我认为,在MacOS中也是如此)。在

(请参阅StackOverflow的Tag Info for zombie-process tag。)

这将产生如下输出:

^{pr2}$

相关问题 更多 >

    热门问题