0

I saw a few threads for this, but everything there didn't help me.

I'm running a subprocess to run commands on cmd via python(using 2.7)

p = subprocess.Popen(["start",  "cmd", "/k", command], shell=True)

This command works and everything, but I can't manage to capture the output of the command.

I tried check_output or specifying stdout=sp.PIPE or stdout=file, but it didn't work.

Any suggestion will be appreciated.

Thanks

1 Answer 1

1

check_output should work fine:

from subprocess import check_output

out = check_output(["echo", "Test"], shell=True)

Output of command:

>>> print out
Test
Sign up to request clarification or add additional context in comments.

9 Comments

Be careful with shell=True though. It can be a security risk (docs.python.org/2/library/…).
is there a difference between sp.check_output(["ipconfig"], shell=True) and sp.Popen(["start", "cmd", "/k", "ipconfig"], shell=True)?
from what i can see option 1 doesn't open cmd, but executes it in python. and option 2 opens it in cmd. but they run the same command
The shell=True is completely useless here anyway; even if you don't care about security, the additional overhead and hidden complexity should scare you. See also stackoverflow.com/questions/3172470/…
Popen() merely starts the process. For a simple process, that may be enough to get you the output, but you should understand that you are responsible for managing the process and cleaning up when it is done. The various subprocess wrappers take care of this for you. Eventually they all call Popen but you should avoid that unless you have complex needs.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.