QProcess.pid()
的文档说:
Returns the native process identifier for the running process, if available. If no process is currently running, 0 is returned.
这是什么意思?
这段代码用来解释我的困惑.我使用的是Python 2.7.9,PyQt 4和Windows 7:
import sys, os, time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class testLaunch(QWidget):
def __init__(self):
QWidget.__init__(self)
self.process = QProcess(self)
self.process.start('calc')
self.process.waitForStarted(1000)
print "PID:", int(self.process.pid())
if __name__ == "__main__":
app = QApplication(sys.argv)
main = testLaunch()
main.show()
sys.exit(app.exec_())
这将按预期启动Windows计算器应用程序.在任务管理器中,它显示以下内容:
这显示我的PID为8304.虽然我的应用程序的print语句显示:
PID: 44353984
这代表了什么?它与任务管理器报告的8304 PID相比如何?
最佳答案 在Unix系统上,pid将是一个qint64,但在Windows上它将是这样的结构:
typedef struct _PROCESS_INFORMATION {
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
PyQt将为这样的结构返回一个sip.voidptr,这就是为什么当你用int()转换它时你会看到这个奇怪的值.你想要的实际pid是dwProcessId,所以你需要使用像ctypes这样的东西来提取它.
这是一些完全未经测试的代码,可以完成这项工作:
import ctypes
class WinProcInfo(ctypes.Structure):
_fields_ = [
('hProcess', ctypes.wintypes.HANDLE),
('hThread', ctypes.wintypes.HANDLE),
('dwProcessID', ctypes.wintypes.DWORD),
('dwThreadID', ctypes.wintypes.DWORD),
]
LPWinProcInfo = ctypes.POINTER(WinProcInfo)
lp = ctypes.cast(int(self.process.pid()), LPWinProcInfo)
print(lp.contents.dwProcessID)