2

I want to open cmd.exe using python, then send several commands sequentially to the cmd.exe and see the output in the same cmd.exe window. How can I do this? Using the following code doesn't show the output in the cmd.exe window.

proc = subprocess.Popen("cmd", creationflags=subprocess.CREATE_NEW_CONSOLE)
proc.communicate("dir\n")
Sunny88
  • 2,860
  • 3
  • 24
  • 25
  • you want `stdin` to come from your Python script, but stdout to go to the new console windows (python script is not in the same window). Is it correct? Why do you need it (could you provide more context)? [Have you considered to use a GUI instead?](http://stackoverflow.com/a/11713013/4279) Here's an example on how to [show subprocess output continiusly in a GUI (using tkinter)](https://gist.github.com/zed/42324397516310c86288) Do you have a full command list or is it interactive? – jfs Dec 09 '13 at 19:35
  • @J.F.Sebastian I am calling curl from my python program. Curl outputs a nice loading bar when it is working, so I want to reuse it. Curl doesn't normally come with windows, so I installed it separately. My program is a sort of simple download manager. – Sunny88 Dec 11 '13 at 05:58
  • @J.F.Sebastian I tried your second link, but it failed to show the curl output in the gui window. – Sunny88 Dec 11 '13 at 05:59
  • `failed to show` is not very informative. My guess would be that curl uses stderr to print the progress but the example captures stdout of the command. – jfs Dec 11 '13 at 06:02

1 Answers1

2

You need to specify stdin=subprocess.PIPE, stdout=subprocess.PIPE. (Also specify stderr=subprocess.PIPE if you want to catch standard error output). Otherwise, Popen.communicate can't send input to subprocess, and can't get output.

import subprocess
proc = subprocess.Popen("cmd", stdin=subprocess.PIPE, stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE)
out, err = proc.communicate("dir\n" "cd ..\n" "dir\n")
# `Popen.communicate` returns a tuple of (standard output, standard error)
print(out)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    Thanks, but this doesn't show the output inside the cmd.exe window. – Sunny88 Dec 09 '13 at 14:15
  • @Sunny88, I get the output of the commands. What do you get if you run the code in my answer? – falsetru Dec 09 '13 at 14:19
  • 1
    I get the output, but it is written in the console from which python script is running, not in the cmd.exe window which the program has spawned. – Sunny88 Dec 09 '13 at 14:22