space_dude
space_dude

Reputation: 3

Dynamic string operations in Python

I am trying to control an external program called foo from python using:

p = Popen(["foo"], stdin=PIPE, stdout=PIPE)
data_out = p.communicate(input_txt[0]+"\n"+input_txt[1]+"\n")[0]

input_txt is a list of commands that gets executed.The code above executes two command lines of program foo: input_txt[0] and input_txt[1] and works just fine. However, the above code runs inside a loop and each time the size of input_txt is different (e.g might need to go up to input_txt[14] or more. How can I dynamically build the above command so that each time it will have the required number of input_txt entries?

One idea is to try and build the command using string operations and then using 'exec' to run it but how would I go about doing that?...and on top of that the newline '\n' character seems to complicate things. Any help will be greatly appreciated. Many thanks!

Upvotes: 0

Views: 108

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

Try this:

input_str = "\n".join(input_txt) + "\n"

This will join the entries of input_txt, separating them with "\n" and appending a trailing "\n" to the end.

You can then use:

data_out = p.communicate(input_str)[0]

Upvotes: 1

Related Questions