问题
The documentation for QProcess.pid() says:
Returns the native process identifier for the running process, if available. If no process is currently running, 0 is returned.
What does this mean?
This code is used to explain my confusion. I am using Python 2.7.9, PyQt 4 and 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_())
This launches the Windows calculator application, as expected. In the task manager, it shows the following:
This shows my PID as 8304. The print
statement from my application though, shows:
PID: 44353984
What does this represent and how does it compare to the 8304 PID the task manager reports?
回答1:
On Unix systems, the pid will be a qint64
, but on Windows it will be struct
like this:
typedef struct _PROCESS_INFORMATION {
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
PyQt will return a sip.voidptr
for such a struct, which is why you are seeing that weird value when you convert it with int()
. The actual pid you want is the dwProcessId
, so you will need to use something like ctypes to extract it.
Here is some completely untested code which might do the job:
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)
来源:https://stackoverflow.com/questions/32509089/when-using-pyqt-on-windows-what-does-the-qprocess-pid-result-represent