How to detect if python script is being run as a background process

廉价感情. 提交于 2019-12-03 06:22:45
BlackJack

Based on the answer for C @AaronDigulla pointed to in a comment:

import os
import sys


def main():
    if os.getpgrp() == os.tcgetpgrp(sys.stdout.fileno()):
        print 'Running in foreground.'
    else:
        print 'Running in background.'


if __name__ == '__main__':
    main()
RomanHotsiy

Based on bash solution from this answer:

import os
import subprocess
pid = os.getpid()
if "+" in subprocess.check_output(["ps", "-o", "stat=", "-p", str(pid)]):
  print "Running in foreground"
else:
  print "Running in background"

I saw the other solutions on other and decided to write a pure python solution. It reads from /proc/<pid>/stat rather than calling a subprocess.

from os import getpid

with open("/proc/{}/stat".format(getpid())) as f:
    data = f.read()

foreground_pid_of_group = data.rsplit(" ", 45)[1]
is_in_foreground = str(getpid()) == foreground_pid_of_group

The meanings of the columns of the stat file can be found here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!