Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
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)