-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
  • 32,724
  • 9
  • 46
  • 70
Artem
  • 23
  • 4

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
  • 760
  • 8
  • 22
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
  • 3,910
  • 3
  • 27
  • 48
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.