Search code examples
pythonbackground-process

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


Is there a way to tell whether my python script is running as a background process or not? I'm trying to differentiate between these two:

sudo ./myscript.py
sudo ./myscript.py &

Using sys.argv doesn't work - the ampersand doesn't count as an argument apparently. And what would be the effect of the following instead:

sudo python myscript.py
sudo python myscript.py &

I've had a look around, but everything seems to be about starting a background process from within a Python script, not whether the Python script itself is a background process. Thanks!

EDIT: The aim is to output a message (or not), i.e. "Press Ctrl+C to stop this script" if started normally, but don't display the message if started as a background process.

EDIT 2 I neglected to mention that this python script will be started by a script in /etc/init.d rather than from a terminal prompt. So the answer marked as correct does indeed answer the question as I phrased it and with the information given, but I thought I should point out that it doesn't work in the init.d scenario, to avoid any potential confusion in the future.


Solution

  • 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()