Python subprocess.Popen 获取派生进程的进程的 pid
我正在启动一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管您已将
-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
.如果您使用:
作为 Popen 命令的参数,您的 pid 将匹配正在运行的 shell 的 pid 而不是命令。只要该进程不是守护进程并且将自身与终端分离,您就应该能够通过添加该进程来终止该进程。(您必须将命令更改为不是列表,而是字符串。
它是在Python文档中:
http://docs.python.org/2/library/subprocess .html#subprocess.Popen.pid
If you use:
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