【问题标题】:Running a python script whenever I close a certain window每当我关闭某个窗口时运行 python 脚本
【发布时间】:2017-02-11 09:33:15
【问题描述】:

我编写了一个简单的 python 脚本,当我运行它时它会备份某个文件夹。现在我想让它在我关闭某个应用程序(我没有编码)时运行。我该怎么做呢?

【问题讨论】:

  • 这有点棘手。。你可能要查找计算机的整个进程列表,并寻找你需要的应用程序,一旦找到,重复该过程直到它不存在,然后运行你的代码。还保存进程的实际 PID,因此如果有多个应用程序实例正在运行,您将没有问题。
  • 对于像我这样的初学者来说,这听起来有点太难了。我想我现在就手动运行它......

标签: python


【解决方案1】:

假设您想在firefox 浏览器退出时备份一个文件夹。
使用ps -A | grep firefox 我们可以看到这样的进程是否存在。 这有点 hacky,但您可以编写一个 Python 脚本来检查此类进程是否每隔 timeout 秒存在一次,如果它之前存在并且不再存在,我们知道它已关闭,因此我们可以进行备份。然后在操作系统启动时永远运行该循环以观察进程状态。

import subprocess
import time


process_name = 'firefox'
cmd = "ps -A | grep {}".format(process_name)
timeout = 3
process_exists = False


while True:
    ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ps.communicate()[0]

    if output:  # Process is open
        process_exists = True
        print('Process is open so we continue the loop')
        time.sleep(timeout)

    elif process_exists and not output:
        # If process existed before and now there is no output, it means that it has been closed
        # So we backup our folder now
        print('backup data here')
        process_exists = False

    else:
        print('Process has not started yet')
        time.sleep(timeout)

使用these answers 在启动时运行此脚本

【讨论】:

    【解决方案2】:

    答案可能不在 Python 中,而是在你的 shell 中。假设bash为shell,firefox为第三方程序,myscript.py为可执行python脚本:

    [prompt]$ firefox && myscript.py
    

    当 firefox 成功结束时,myscript.py 会运行。您可以将其包装在启动器脚本中。

    如果 Firefox 出现错误,您可以使用 || 代替 && 运行 myscript.py。或者; 运行脚本,不管firefox如何结束。

    此解决方案不涉及轮询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-20
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      相关资源
      最近更新 更多