0

I am executing cmd commands using python subprocess module. Execution of this cmd commands (eg., running some batch file, .exe file) are opening new command prompt window. How to read output of newly open cmd window using python?

I am using following code to execute commands provided by user:

process = subprocess.Popen(command, cwd = working_directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

I am using process.communicate() method to read the output. However it is allowing me to read output of the existing command prompt window only. If user is providing command which triggers new command prompt window, then how to read output of that window?

  • https://docs.python.org/3/library/subprocess.html#subprocess.check_output – lemonhead Dec 19 '17 at 09:25
  • What have u tried so far? – pankaj mishra Dec 19 '17 at 10:16
  • @pankajmishra I am using following code to execute the cmd commands provided by use. If user provides command which is opening new command window, then I am looking for solution to read output from the newly opened command window. Till now I am only able to read output from existing cmd window and not the newly opened window. Thanks for your consideration in advance. :) `process = subprocess.Popen(command, cwd = working_directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)` – Shreyansh prajapati Dec 20 '17 at 06:26
  • Paste this code into your question – pankaj mishra Dec 20 '17 at 06:27
  • see my answer and let me know what is not working for u – pankaj mishra Dec 20 '17 at 06:52

1 Answers1

1

Below code opens a new command prompt, execute a command there and display the output of that command window

from subprocess import Popen,CREATE_NEW_CONSOLE,PIPE

# /K option tells cmd to run the command and keep the command window from closing. You may use /C instead to close the command window after the 

command='cmd /C help'
proc=Popen(command,creationflags=CREATE_NEW_CONSOLE,stdout=PIPE)
output=proc.communicate()[0]
print ('').join(output)
pankaj mishra
  • 2,555
  • 2
  • 17
  • 31