Wrapping cmd.exe with subprocess

I am trying to wrap cmd.exe under the windows with the following program, but it does not work, it seems that it is waiting and does not display anything. Any idea what's wrong here?

import subprocess

process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)  
process.stdin.write("dir\r\n")  
output = process.stdout.readlines()  
print output
+3
source share
3 answers

This is blocked because it process.stdout.readlines()reads the entire output of the process (until it ends). Since cmd.exe is still running, it waits all the time for it to close.

, , . , , communicate(), . process.stdout.readline() .

+2
process = subprocess.Popen('cmd.exe /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.write("dir\n")
o,e=process.communicate()
print o
process.stdin.close()
, , os- Python, os.listdir() glob-... .. , .
+5

Usually, when you try to invoke the command line using the actual command, it is easier to just call it with the "/ k" parameter, rather than passing commands through stdin. That is, just name "cmd.exe / k dir". For instance,

from os import *
a = popen("cmd /k dir")
print (a.read())

The code below does the same thing, although you are missing a line to manipulate, since it directly outputs the output:

from subprocess import *
Popen("cmd /k dir")
+4
source

Source: https://habr.com/ru/post/1727781/


All Articles