python:在Windows中使用createprocessasuser api时处理stderr流

时间:2014-08-01 04:31:17

标签: python windows createprocessasuser

需要一些帮助调试此问题。我尝试在线搜索和stackoverflow但无法找到解决方案。我对windows api相当陌生,所以请原谅我的无知。

基本上,我正在尝试运行一个c ++应用程序,它使用特定用户从python输出到stdout和stderr。为此,我使用LogonUser API和CreateProcessAsUser apis调用二进制文件,并使用Pipes捕获输出和错误流。已经从python win32模块中的演示代码中获取了代码。但是,出于某种原因,当我的进程转储到错误流时,它会在WriteFile中挂起。查看崩溃转储,我看到文件句柄是2(stderr)。有人可以帮我解决这个问题吗?

提前致谢

以下是代码段 -

userToken = win32security.LogonUser(user, domain, password,
                                    win32con.LOGON32_LOGON_BATCH,
                                    win32con.LOGON32_PROVIDER_DEFAULT)

secAttrs = win32security.SECURITY_ATTRIBUTES()
secAttrs.bInheritHandle = 1
stdout_r, stdout_w = win32pipe.CreatePipe(secAttrs, 0)
stderr_r, stderr_w = win32pipe.CreatePipe(secAttrs, 0)

startupInfo = win32process.STARTUPINFO()
startupInfo.dwFlags = win32con.STARTF_USESTDHANDLES
startupInfo.hStdOutput = stdout_w
startupInfo.hStdError = stderr_w

ppid = win32api.GetCurrentProcess()
tmp = win32api.DuplicateHandle(ppid, stdout_r, ppid, 0, 0,
                               win32con.DUPLICATE_SAME_ACCESS)
win32file.CloseHandle(stdout_r)
stdout_r = tmp

procArgs = (None,       # appName
            cmd_line,   # commandLine
            None,       # processAttributes
            None,       # threadAttributes
            1,          # bInheritHandles
            win32process.CREATE_NEW_CONSOLE, # dwCreationFlags
            None,       # newEnvironment
            None,       # currentDirectory
            startupInfo)

procHandles = win32process.CreateProcessAsUser(userToken, *procArgs)

win32file.CloseHandle(stderr_w)
win32file.CloseHandle(stdout_w)
win32security.RevertToSelf()

# Wait for process to complete
hProcess, hThread, pid, tid = procHandles

stdout_buf = os.fdopen(msvcrt.open_osfhandle(stdout_r, 0), "rb")
stdout = stdout_buf.read()
stderr_buf = os.fdopen(msvcrt.open_osfhandle(stderr_r, 0), "rb")
stderr = stderr_buf.read()

win32event.WaitForSingleObject(hProcess, 3600*1000)
rc = win32process.GetExitCodeProcess(hProcess)

0 个答案:

没有答案