【问题标题】:QProcess cannot write to cmd.exeQProcess 无法写入 cmd.exe
【发布时间】:2012-11-08 04:39:36
【问题描述】:

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

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

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

{时间流逝}

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

那么“dir \n”命令是否从未发出?

【问题讨论】:

    标签: python qt cmd pyside qprocess


    【解决方案1】:

    看起来您需要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'
    

    【讨论】:

      【解决方案2】:

      您的代码存在几个问题。

      1. 将空字符串作为参数传递(显然)不是一个好主意
      2. start(...) 方法不返回值,但 waitForStarted() 可以
      3. 在致电readAllStandardOutput() 之前致电waitForReadyRead()
      4. waitForFinished() 不会返回(或只是超时),除非您让进程 (cmd.exe) 真正退出

      这应该是您示例中的最小工作版本:

      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()))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多