QProcess无法写入cmd.exe

4
我似乎无法通过 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"命令从未被执行吗?
2个回答

0

看起来你需要在读取输出之前关闭写通道

这对我在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'

0

你的代码存在几个问题:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接