Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the output of shell instantly by python script

Tags:

python

I executed some commands in shell with python. I need to show the command response in shell. But the commands will execute 10s . I need to wait. How can I show the echo of the commands instantly. Following is my code

cmd = "commands"
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
print(output.stdout.read())     

And I need to use the output of the command. so I can't use subprocess.call

like image 271
Samuel Avatar asked Oct 21 '22 20:10

Samuel


1 Answers

Read from output.stdout in a loop:

cmd = "commands"
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in output.stdout:
    print(line)

edit: seems then in python2 this still doesn't work in evey case, but this will:

for line in iter(output.stdout.readline, ''):
    print(line)
like image 135
mata Avatar answered Oct 23 '22 09:10

mata