【发布时间】:2016-02-21 09:08:23
【问题描述】:
我目前正在编写我的第一个 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 完成我的任务?
【问题讨论】:
-
在需要的时候使用
communicate就行了..你不需要检查结果吗?只是避免它... -
@klashxx:我确实需要结果。那是我的问题...(需要检查“服务器以 RUNNING 模式启动”的输出...)
-
@daTokenizer:所以解决方案是避免 subprocess.Popen 并使用 sytem() 或 os.spawn 并分别检查输出?
标签: python linux bash subprocess daemon