Python lib subprocess

Asked

Viewed 174 times

1

Does anyone know why he 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)

1 answer

1

cmd points to a list, which is a mutable object. This means that when you extend cmd for the second time you modify the value still 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, it is only possible to execute one command at a time and "ls-la" being the first in cmd, will be executed in the two 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 object cmd for each command we get a term instance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.