TomSelleck
TomSelleck

Reputation: 6968

Capture output of Popen when shell=True

Command prompt:

C:\Users\Documents\libexe\tfc\bin\Debug>asc-dir
asc-dir.: directory not linked to an ASC directory //Expected output

Test Script:

proc = subprocess.Popen('asc-dir', stdout=subprocess.PIPE, shell = True)
(result, err) = proc.communicate()

This prints "asc-dir.: directory not linked to an ASC directory" to the console but is not saved to result or err.

How can I save the output to result / err?

When I try Popen with shell=False, I get the following error:

Error:
    WindowsError: [Error 2] The system cannot find the file specified
    Press any key to continue . . .

Upvotes: 0

Views: 1643

Answers (2)

Jahaja
Jahaja

Reputation: 3302

Add stderr=subprocess.PIPE to Popen. Otherwise, the standard error will continue to go to whatever file the subprocess inherits from your script.

Upvotes: 3

Tom Dalton
Tom Dalton

Reputation: 6190

Remove shell=True unless you actually need it. It sounds like the real problem is that Windows cannot find the asc-dir executable. Where is it installed/located? Is that directory in the PATH environment variable? If not, you could either add it, or specify the full path to the executable when you call Popen e.g.

proc = subprocess.Popen(r'C:\program files\asc\bin\asc-dir', stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Upvotes: 0

Related Questions