user8087992
user8087992

Reputation:

Why is Popen("cmd.exe echo a", shell=True) not running "echo"?

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>.

Upvotes: 1

Views: 1747

Answers (2)

BoarGules
BoarGules

Reputation: 16942

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.

Upvotes: 3

Charles Duffy
Charles Duffy

Reputation: 295403

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

Upvotes: 2

Related Questions