QProcess无法写入cmd.exe

时间:2012-11-20 06:29:16

标签: python qt cmd pyside qprocess

我似乎无法让QProcess通过cmd.exe将命令传递给stdin。我也尝试过其他命令行应用程序。

以下是我用来尝试和调试的一些简单代码:

prog = "c:/windows/system32/cmd.exe"
arg = [""]
p = QtCore.QProcess()
retval = p.start(prog, arg)
print retval
print p.environment()
print p.error()
p.waitForStarted()
print("Started")
p.write("dir \n")
time.sleep(2)
print(p.readAllStandardOutput())
print(p.readAllStandardError())
p.waitForFinished()
print("Finished")
print p.ExitStatus()

输出:

None
[]
PySide.QtCore.QProcess.ProcessError.UnknownError
Started

{time passes}

Finished
PySide.QtCore.QProcess.ExitStatus.NormalExit
QProcess: Destroyed while process is still running.

dir \n”命令从未发出过吗?

2 个答案:

答案 0 :(得分:0)

在阅读输出之前,您似乎需要close the write channel

这适用于WinXP:

from PySide import QtCore

process = QtCore.QProcess()
process.start('cmd.exe')

if process.waitForStarted(1000):

    # clear version message
    process.waitForFinished(100)
    process.readAllStandardOutput()

    # send command
    process.write('dir \n')
    process.closeWriteChannel()
    process.waitForFinished(100)

    # read and print output
    print process.readAllStandardOutput()

else:
    print 'Could not start process'

答案 1 :(得分:0)

您的代码存在一些问题。

  1. 传递空字符串作为参数(显然)不是一个好主意
  2. start(...)方法不会返回值,但waitForStarted()会返回
  3. 在致电readAllStandardOutput()之前致电waitForReadyRead()
  4. 除非您使进程(cmd.exe)实际退出,否则
  5. waitForFinished()将不会返回(或仅仅超时)
  6. 对于您的示例,这应该是最小的工作版本:

    from PySide import QtCore
    
    prog = "cmd.exe"
    arg = []
    p = QtCore.QProcess()
    p.start(prog, arg)
    print(p.waitForStarted())
    
    p.write("dir \n")
    p.waitForReadyRead()
    print(p.readAllStandardOutput())
    
    p.write("exit\n")
    p.waitForFinished()
    print("Finished: " + str(p.ExitStatus()))