2

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?

4

1 回答 1

2

apt-get update命令也以标准错误返回数据,因此您还需要捕获stderr数据:

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

然后你必须同时使用Popen.stdoutPopen.stderr

于 2012-11-02T09:43:46.417 回答