QProcess无法写入命令行

2024-04-26 17:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎无法让QProcess通过stdincmd.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()

输出:

^{pr2}$

{时间流逝}

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

那么“dir \n”命令从未发出过吗?在


Tags: 命令行命令cmd应用程序dirstdinargexe
2条回答

在读取输出之前似乎需要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. 传递一个空字符串作为参数(显然)不是一个好主意
  2. start(...)方法不返回值,但waitForStarted()返回值
  3. 在调用readAllStandardOutput()之前,调用waitForReadyRead()。在
  4. waitForFinished()将不会返回(或仅超时),除非您执行该过程(命令提示符)实际退出

对于您的示例,这应该是一个最基本的工作版本:

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

相关问题 更多 >