问题描述
有没有办法判断我的python脚本是否正在作为后台进程运行?我试图区分这两个:
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 &
使用sys.argv
不起作用-显然,&"号不算作参数.而以下内容的结果将是什么:
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 &
我环顾四周,但是似乎所有事情都与从Python脚本中启动后台进程有关,而不是与Python脚本本身是否是后台进程无关.谢谢!
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!
目的是(正常情况下)输出(或不输出) ie "Press Ctrl+C to stop this script"
消息,但如果以后台进程.
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.
编辑2 我忽略了提及此python脚本将由以下脚本中的一个启动/etc/init.d
,而不是在终端提示符下.因此,标记为正确的答案确实可以按照我的表述和给出的信息回答该问题,但是我想指出,在init.d
场景中它不起作用,以避免将来出现任何潜在的混乱.
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.
推荐答案
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()
这篇关于如何检测python脚本是否正在作为后台进程运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!