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

Mumfordwiz
  • 1,483
  • 4
  • 19
  • 31

1 Answers1

1

check_output should work fine:

from subprocess import check_output

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

Output of command:

>>> print out
Test
Farhan.K
  • 3,425
  • 2
  • 15
  • 26
  • 2
    Be careful with `shell=True` though. It can be a security risk (https://docs.python.org/2/library/subprocess.html#frequently-used-arguments). – Farhan.K Mar 15 '16 at 09:53
  • is there a difference between `sp.check_output(["ipconfig"], shell=True)` and `sp.Popen(["start", "cmd", "/k", "ipconfig"], shell=True)`? – Mumfordwiz Mar 15 '16 at 09:56
  • 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 – Mumfordwiz Mar 15 '16 at 09:56
  • 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 http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee Mar 15 '16 at 10:01
  • `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. – tripleee Mar 15 '16 at 10:02
  • I meant as a cmd command. is there any difference? because option 2 opens a cmd window and runs the command there, option 1 runs a cmd command on python – Mumfordwiz Mar 15 '16 at 10:20
  • It doesn't run "on python" but certainly as a subprocess of Python. If you wanted to ask about the difference between `cmd` and no `cmd`, why does one have `check_output` and the other `Popen`? Those are quite different. In the meantime, sure, you can wrap arbitrary levels of external tools, or, say, `python -c 'os.system("python -c \"os.system(\"\"python ...` and eventually produce the same end result, but why would you? – tripleee Mar 15 '16 at 10:27
  • @tripleee Yes `shell=True` is useless, but for my specific example it was required. – Farhan.K Mar 15 '16 at 11:12
  • On Windows that is, I know it's different on Linux – Farhan.K Mar 15 '16 at 11:18