Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 子流程pid与ps输出不同_Python_Subprocess_Pid_Ps - Fatal编程技术网

Python 子流程pid与ps输出不同

Python 子流程pid与ps输出不同,python,subprocess,pid,ps,Python,Subprocess,Pid,Ps,为什么子进程pid(Popen.pid)的值与ps命令返回的值不同 当从python内部(使用subprocess.call())和另一个终端调用ps时,我注意到了这一点 下面是一个要测试的简单python文件: #!/usr/bin/python3 ''' Test subprocess termination ''' import subprocess command = 'cat' #keep pipes so that cat doesn't complain proc = sub

为什么子进程pid(
Popen.pid
)的值与
ps
命令返回的值不同

当从python内部(使用
subprocess.call()
)和另一个终端调用
ps
时,我注意到了这一点

下面是一个要测试的简单python文件:

#!/usr/bin/python3
'''
Test subprocess termination
'''

import subprocess

command = 'cat'

#keep pipes so that cat doesn't complain
proc = subprocess.Popen(command,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    shell=True)

print('pid = %d' % proc.pid)
subprocess.call("ps -A | grep -w %s" % command,
                    shell=True)

proc.terminate()
proc.wait()             # make sure its dead before exiting pytyhon

通常,
ps
报告的pid比
Popen.pid

报告的pid多1或2个,因为命令是在
shell=True
下运行的,所以子进程返回的pid是用于运行命令的shell进程的pid。

它在我的mac上工作。您确定没有在
ps
输出中查看
grep命令
pid吗?在我的mac上,
ps-A | grep
列出了三个进程-
cat
/bin/sh-cps-A | grep-wcat
grep-wcat
。我刚刚意识到-可能
Popen.pid
是shell进程id,ps | grep报告了
cat
的pid?是的。它是
shell=True
。有人发布了答案,但它似乎不再在这里了。。。不管是谁,请重新发布以便我可以接受。有趣的是,引用生成的shell的pid也可能会干扰terminate()和kill()。或者至少看起来是这样,因为信号被发送到shell而不是所需的子进程。您可以对此进行扩展吗?我试图使用subprocess打开一个ssh隧道,并遇到与OP相同的问题,其中
进程.pid
不是实际值,但使用
shell=True
shell=False
运行函数似乎不会改变任何东西。