Welcome to the Treehouse Community
Looking to learn something new?
Welby Obeng20,340 Points
how to add for loop in a string command
I am trying to run a command in python using subprocess.call. The end results should be
subprocess.call("blah blah blah ",,shell=True)
I have list with list of parameters that I want to put between "blah blah blah "
[['blah1', 'blah2'], ['blah1', 'blah2'])
how do I put this in the string of subprocess.call so that when it's executed it will be a string
Gavin Ralston28,770 Points
Ok so,the Python Docs for this provide the following example:
So your first argument can be a list, where the first element is the command, the remaining is a series of flags. You could do this:
subprocess.call(["ls", "-l", "-a", "-h"])
or whatever you wanted for that first argument, then add whatever other arguments you wanted afterward, just like normal (shell=True, etc)
So now really all you need to do is figure out a way to run through the list of flags you want and append (or extend, depending on how you do it) your command list, then put it into the call method. Like
#presumably this is a list of flags you built with a for..in loop flags = ['-l', '-h'] my_command = ["ls"].extend(flags) subprocess.call(my_command, shell=True)