如何在python中启动进程并将其置于后台?

2024-10-03 17:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写我的第一个python程序(用python2.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脚本调用应用程序的启动脚本:

^{pr2}$

bash脚本是从python代码调用的。这个解决方案工作得很完美,但我更喜欢用python做所有的事情。。。在

是子流程.Popen走错了路?我怎么能只用Python来完成我的任务呢?在


Tags: 用户程序服务器脚本bash应用程序outputlinux
1条回答
网友
1楼 · 发布于 2024-10-03 17:24:57

首先,在通信中很容易不阻塞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之类的不需要的信号。如果要使其成为守护进程,则必须首先启动下一个启动服务器的子进程。这样,当第一个子进程结束时,调用者可以等待它,服务器将得到一个PPID 1(由init进程采用)。您可以使用多处理模块来简化这一部分

代码可以是:

^{pr2}$

有人可能想知道,当一个文件对象本身是一个每次返回一行的迭代器时,对getlines生成器的需求是什么。问题是它在内部调用read,当文件未连接到终端时,它一直读到EOF。由于它现在已连接到管道,在服务器结束之前您将无法获得任何内容。。。这是不是所期望的

相关问题 更多 >