1

This leads to a bigger problem I am having here with Popen().

The following does not do what I thought it should:

x = subprocess.Popen("cmd.exe echo a", stdout=PIPE, shell=True)
print (x.stdout.read())

Returns the "title" message of the cmd console, but echo a is never executed.

Same with:

x = subprocess.Popen(["cmd.exe", "echo a"], stdout=PIPE)
print (x.stdout.read())

and

cmd = "cmd.exe echo a"
x = subprocess.Popen(shlex.split(cmd), stdout=PIPE)
print (x.stdout.read())

End result is in open cmd terminal that prints the standard "Microsoft Windows version..." and a CLI position of C:\Python36>.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441

2 Answers2

3

The command processor cmd.exe is implicit when you specify shell=True.

>>> x = subprocess.Popen("echo a", stdout=subprocess.PIPE, shell=True)
>>> print (x.stdout.read())
a

By invoking it explicitly you fire up a nested command console, as if you had typed cmd.exe at the prompt. Its output doesn't go to Popen()'s pipe.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
2

cmd.exe requires the argument /c to precede a script being passed for execution:

x = subprocess.Popen(["cmd.exe", "/c", "echo a"], stdout=PIPE)
print (x.stdout.read())
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Now what if I wanted the `stdout` of say `C:\Users\Me> C:\path\to\app.exe arg1 arg2`? If I open a cmd console and supply the .exe path and args, the output is produced to `stdout` but I cant seem to replicate with `subprocess` as outline in my link in the OP. –  Jun 05 '17 at 15:31