获取在另一个终端中执行的 python 进程的状态

Get the status of a python process that was executed in another terminal

我有一个 python 程序,它将在新终端中创建并执行另一个 python 脚本。为此,我使用 subprocess.Popen。我正在尝试使用 .pid 获取新进程的 PID。但是,这个 pid 的值似乎与新创建进程的真实 pid 不匹配(两个值不匹配)。

这是我的代码示例:

from subprocess import Popen

p = Popen("gnome-terminal -e 'python'",shell = True)
print p.pid

在新打开的终端中,我尝试使用以下方法获取 pid:

import os
print os.getpid()

我得到两个不同的值。有谁知道如何获得正确的pid?我需要知道第二个过程何时完成,以便在第一个过程中执行操作。

感谢您的帮助!

如果您需要更多详细信息,请告诉我:)

根据 documentation.

如果将 shell 参数设置为 True,这是生成的进程 ID shell。

所以你需要shell=False

However, the value of this pid doesn't seem to match the real pid of the newly created process (the two values don't match).

这里有3个过程:shell=True导致/bin/sh到运行那个运行sgnome-terminal那个运行spython(也许是间接的)。 gnome-terminal 可能只是一个启动程序,它将启动 python 委托给 运行ning 服务器进程并退出。

shell=False 在这里无济于事。您将获得 gnome 终端的 pid 而不是 /bin/sh——您不会获得 python 进程的 pid。

您可以将 pid 写入已知文件或通过 pipe/socket 进行通信。