4

I cannot seem to get QProcess to pass commands to cmd.exe via stdin. I have tried other command line apps as well.

Here is some simple code that I use to try and debug:

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

The output:

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

{time passes}

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

So is the "dir \n" command never issued?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
user1837845
  • 41
  • 1
  • 2

2 Answers2

0

It looks like you need to close the write channel before reading the output.

This works for me on 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'
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
0

There are a couple of issues with your code.

  1. passing an empty string as an argument is (apparently) not a good idea
  2. the start(...) method does not return a value, but waitForStarted() does
  3. before calling readAllStandardOutput() call waitForReadyRead().
  4. waitForFinished() will not return (or merely time out) unless you make the process (cmd.exe) to actually exit

This should be a minimal working version along the lines for your example:

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()))
axxel
  • 1,009
  • 7
  • 11