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! While you're at it, check out some resources Treehouse students have shared here.

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

Python

Welby Obeng
Welby Obeng
20,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 Ralston
Gavin Ralston
28,770 Points

When you say you're trying to put a list of "blah blah" between the "blah" command, could you be a little more precise?

Are you looking to pass a list of arguments to the process you want to call, or are you looking to change the command you're issuing to the os?

Is there any chance you could provide something more concrete than "blah" in both examples to make it a little easier to follow what you're trying to do?

Welby Obeng
Welby Obeng
20,340 Points

I'm looking to pass a list of arguments to the process I want to call.

1 Answer

Gavin Ralston
Gavin Ralston
28,770 Points

Ok so,the Python Docs for this provide the following example:

subprocess.call(["ls", "-l"])

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", "-lah"])

or 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)