python - 当某个应用程序在 Python 中启动时如何触发函数

标签 python python-3.x linux background-process

假设一个 python 脚本在后台运行,当我在我的计算机 (Linux) 上启动某个应用程序/软件时,我如何触发脚本内的函数。

我在谷歌上搜索了很多,但找不到解决方案!

提前谢谢你。

最佳答案

假设,您必须在外部进程“abc”启动时调用函数 callemnow。有多种方法可以做到这一点,但下面是一个示例代码,您可以轻松理解。

Note: ps -eaf | grep will give process details. The same command you can call from python script vi subprocess.

while True is just for the convenience. You have to substitute that statement as per your logic flow

from subprocess import Popen, PIPE

def externalprocess():
    cmd = Popen(['ps', '-eaf'],stdout=PIPE)
    (output, err) = cmd.communicate()
    return True if "abs" in output else False

def callmenow()
    '''
    your logic
    '''

if __name__ == '__main':
    while True:
        if externalprocess():
            callmenow()

关于python - 当某个应用程序在 Python 中启动时如何触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58004600/

相关文章:

python - Django 1.1 - 评论 - 'render_comment_form' 返回 TemplateSyntaxError

python-3.x - Scrapy:嵌套选择器:子选择器在所有页面上运行,而不是在父选择器上运行

linux - 我们可以使用 quilt 推送/添加到本地 git 存储库吗?

python - 如何使用当前的电子邮件库附加txt文件?

python - Django URL反向: When URL reversig a username it fails when username has a '.' literal in it

python - 如何从字符串中删除所有空格

python-3.x - 在 Windows 7 下使用 python 3.3 (Anaconda) 构建最小的 cython 文件

c - GCC linux 5.1 在比较有符号和无符号整数时不发出警告

linux - pppd: peer 拒绝同意我们的 IP 地址

python - Python 中的站点包