-1

I want to do something like this

CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']
for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[1])

How can i do list of commands in for loop?

CristiFati
  • 38,250
  • 9
  • 50
  • 87
Artem
  • 33
  • 5

3 Answers3

1

In subprocess you must provide your command as a list, with the first item being the command and each following item being the arguments.

In your case your code should look like:

CMD_LIST = [['ls', '-l'], ['echo', 'Mama Mia'], ['echo', 'bla bla bla']]
for cmd_arg in CMD_LIST:
    subprocess.call(cmd_arg)

See subprocess docs here: https://docs.python.org/2/library/subprocess.html

JamoBox
  • 764
  • 9
  • 23
0

CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']

for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[i])

Did you mean this?

User_Targaryen
  • 4,125
  • 4
  • 30
  • 51
0

Python lets you loop directly over iterables like your command list

for cmd in CMD_LIST:
    subprocess.call(cmd)

This is much more readable and avoids errors in indexed looping.