Python subprocess.Popen 获取派生进程的进程的 pid

发布于 2024-10-17 15:26:15 字数 333 浏览 2 评论 0原文

我正在启动一个 ssh 命令,该命令将自行分叉,并且即使在脚本完成后也会运行。所以代码看起来像这样:

ssh_proc = Popen(['ssh', '-f', '-N', '-L', local_forward, local_user_host], stdin=PIPE, stdout=PIPE)
print ssh_proc.pid
stat = ssh_proc.poll()

正如你所看到的 ssh -f 将 ssh 分叉为一个进程并在脚本完成后运行 - 我需要获取该 ssh 进程的 pid。上面的 print 语句只会打印出 Popen 进程的 pid。有什么建议吗?

I am firing up an ssh command that will fork itself out and will be running even after the script is done. So the code looks like this:

ssh_proc = Popen(['ssh', '-f', '-N', '-L', local_forward, local_user_host], stdin=PIPE, stdout=PIPE)
print ssh_proc.pid
stat = ssh_proc.poll()

As you can see ssh -f forks ssh as a process and runs after the script is done - i need to get the pid of that ssh process. The print statement above, will only print out the pid of Popen process. Any suggestions?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心凉怎暖 2024-10-24 15:26:15

尽管您已将 -f 开关传递给 ssh,但您的程序无法控制(且无法获知)ssh 程序本身执行的活动。您的程序没有直接的方法来发现 ssh 已分叉并找到第二个子 pid。

然而,可能有一种间接的方式来获取此信息。您可以枚举活动进程并查找其ssh_proc.pid的进程。

Although you have passed the -f switch to ssh, your program is not in control (and not informed) about what activities the ssh program itself does. There is no direct way for your program to discover that ssh has forked and to find the second child pid.

There may be an indirect way to obtain this information, however. You could enumerate the active processes and look for one whose parent is the ssh_proc.pid.

嘿咻 2024-10-24 15:26:15

如果您使用:

shell=True

作为 Popen 命令的参数,您的 pid 将匹配正在运行的 shell 的 pid 而不是命令。只要该进程不是守护进程并且将自身与终端分离,您就应该能够通过添加该进程来终止该进程。(您必须将命令更改为不是列表,而是字符串。

它是在Python文档中:
http://docs.python.org/2/library/subprocess .html#subprocess.Popen.pid

If you use:

shell=True

as a parameter with your Popen command, your pid will match the running shell's pid instead of the command. As long as the process isn't a daemon and detaches itself from the terminal, you should be able to kill the process just by adding that in. (You would have to change the command to NOT be a list, but a string.

It's in the python docs:
http://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文