gpt4 book ai didi

python - 如何启动一个进程并将其置于 python 后台?

转载 作者:IT王子 更新时间:2023-10-29 00:40:32 25 4
gpt4 key购买 nike

我目前正在编写我的第一个 python 程序(在 Python 2.6.6 中)。该程序有助于启动和停止在服务器上运行的不同应用程序,提供用户常用命令(例如在 Linux 服务器上启动和停止系统服务)。

我正在通过

启动应用程序的启动脚本
p = subprocess.Popen(startCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate()
print(output)

问题是,一个应用程序的启动脚本停留在前台,因此 p.communicate() 永远等待。我已经尝试在 startCommand 前面使用“nohup startCommand &”,但没有按预期工作。

作为解决方法,我现在使用以下 bash 脚本来调用应用程序的启动脚本:

#!/bin/bash

LOGFILE="/opt/scripts/bin/logs/SomeServerApplicationStart.log"

nohup /opt/someDir/startSomeServerApplication.sh >${LOGFILE} 2>&1 &

STARTUPOK=$(tail -1 ${LOGFILE} | grep "Server started in RUNNING mode" | wc -l)
COUNTER=0

while [ $STARTUPOK -ne 1 ] && [ $COUNTER -lt 100 ]; do
STARTUPOK=$(tail -1 logs/SomeServerApplicationStart.log | grep "Server started in RUNNING mode" | wc -l)
if (( STARTUPOK )); then
echo "STARTUP OK"
exit 0
fi
sleep 1
COUNTER=$(( $COUNTER + 1 ))
done

echo "STARTUP FAILED"

bash 脚本是从我的 python 代码中调用的。这个解决方法很完美,但我更愿意在 python 中完成所有操作......

是不是subprocess.Popen方式不对?我怎样才能只用 Python 完成我的任务?

最佳答案

首先,不调用通信很容易不阻塞 Python 脚本...通过不调用通信!只需从命令的输出或错误输出中读取,直到找到正确的消息并忘记该命令。

# to avoid waiting for an EOF on a pipe ...
def getlines(fd):
line = bytearray()
c = None
while True:
c = fd.read(1)
if c is None:
return
line += c
if c == '\n':
yield str(line)
del line[:]

p = subprocess.Popen(startCommand, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) # send stderr to stdout, same as 2>&1 for bash
for line in getlines(p.stdout):
if "Server started in RUNNING mode" in line:
print("STARTUP OK")
break
else: # end of input without getting startup message
print("STARTUP FAILED")
p.poll() # get status from child to avoid a zombie
# other error processing

上面的问题是,服务器仍然是 Python 进程的子进程,并且可能会收到不需要的信号,例如 SIGHUP。如果你想让它成为一个守护进程,你必须先启动一个子进程,然后再启动你的服务器。这样当第一个 child 结束时,调用者可以等待它并且服务器将获得 1 的 PPID(由 init 进程采用)。您可以使用多处理模块来简化该部分

代码可能是这样的:

import multiprocessing
import subprocess

# to avoid waiting for an EOF on a pipe ...
def getlines(fd):
line = bytearray()
c = None
while True:
c = fd.read(1)
if c is None:
return
line += c
if c == '\n':
yield str(line)
del line[:]

def start_child(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
shell=True)
for line in getlines(p.stdout):
print line
if "Server started in RUNNING mode" in line:
print "STARTUP OK"
break
else:
print "STARTUP FAILED"

def main():
# other stuff in program
p = multiprocessing.Process(target = start_child, args = (server_program,))
p.start()
p.join()
print "DONE"
# other stuff in program

# protect program startup for multiprocessing module
if __name__ == '__main__':
main()

当文件对象本身就是一次返回一行的迭代器时,人们可能想知道 getlines 生成器有什么必要。问题是它在内部调用 read ,当文件未连接到终端时读取直到 EOF。因为它现在连接到一个 PIPE,所以在服务器结束之前你不会得到任何东西......这不是所期望的

关于python - 如何启动一个进程并将其置于 python 后台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33800254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com