Python lib subprocess

1

Does anyone know why it opens the 2 terminals with the same command "ls -la"?

import subprocess

cmd = ["xterm"]

cmd.extend(['-e','bash','-c', 'ls -la; exec $SHELL'])

subprocess.Popen(cmd, stdout=subprocess.PIPE)

cmd.extend(['-e','bash','-c','ping google.com; exec $SHELL'])

.Popen(cmd, stdout=subprocess.PIPE)
    
asked by anonymous 22.01.2015 / 20:20

1 answer

1

cmd points to a list, which is a mutable object. This means that when you extend cmd a second time you modify the value of the same object, and that's what you have:

>>> cmd.extend(['-e','bash','-c', 'ls -la; exec $SHELL'])
>>> cmd.extend(['-e','bash','-c','ping google.com; exec $SHELL'])
>>> cmd
['xterm', '-e', 'bash', '-c', 'ls -la; exec $SHELL', '-e', 'bash', '-c', 'ping google.com; exec $SHELL']

Since in this case you can only execute one command at a time, and "ls -la" is the first one in cmd , it will run on both subprocess.Popen () calls. Maybe what you want is this:

import subprocess

cmd = ["xterm"]

cmd.extend(['-e','bash','-c', 'ls -la; exec $SHELL'])
subprocess.Popen(cmd, stdout=subprocess.PIPE)
# novo comando, subscreve objeto
cmd = ["xterm"]

cmd.extend(['-e','bash','-c','ping google.com; exec $SHELL'])
subprocess.Popen(cmd, stdout=subprocess.PIPE)

Subscribing to the cmd object we get for each command a term instance.

29.01.2015 / 22:34