I implemented a python program using subprocess.Popen to execute commands from server to Ubuntu client. The subprocess must read all outputs line by line. My program operates perfectly in Eclipse environment. All outputs print as I expected. But when I run the program under Python interactive shell (in both Windows and Linux), subprocess.Popen didnot read all command outputs. The outputs only show little and then Python crashes without any error. Here is my program codes:
def execute(self, IP_Instance, command):
keypairs_directory = Config.keypairs_directory
cmd = 'ssh ubuntu@%s'%IP_Instance+' -i %s'%keypairs_directory+' %s'%command
cmd_run = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
for line in cmd_run.stdout:
print line
cmd_run.wait()
For example, when I send a command:
a.execute('xxx.xxx.xxx.xxx', 'ls -l')
I have output
total 0
It is OK. But when I send:
a.execute('xxx.xxx.xxx.xxx', 'sudo apt-get update')
The program only runs to
Fetched 8,364 kB in 6s (1,205 kB/s)
Reading package lists...
and then Python backs to
>>>
I had tried communicate()[0], poll() but they did not bring effectiveness. I use Python 2.7 for all machines. What am I doing wrong?