Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
1  
How does returning to the interactive prompt map to "crashes without any error"? What do you get for the return code if you instead return cmd_run.wait()? – eryksun Nov 2 '12 at 10:55

The apt-get update command returns data also in standard error, so you need to catch also stderr data:

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

and then you have to use both Popen.stdout and Popen.stderr.

share|improve this answer
    
Thank for your fast answer. I have just tried this but unfortunately the result is still the same. – Nguyen Minh Nov 2 '12 at 9:53
1  
stderr=subprocess.STDOUT will redirect stderr. – eryksun Nov 2 '12 at 10:04
    
I get the same outputs. Besides, I try other commands that print a long output and the program also cannot read to print all. For instance sudo apt-get install -y mc. However, in Eclipse, all operate exactly. – Nguyen Minh Nov 2 '12 at 10:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.