[英]Dynamic string operations in Python
I am trying to control an external program called foo from python using: 我试图使用以下命令从python控制一个名为foo的外部程序:
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. input_txt是要执行的命令的列表。上面的代码执行程序foo的两条命令行:input_txt [0]和input_txt [1],并且工作正常。 However, the above code runs inside a loop and each time the size of input_txt is different (eg 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?
但是,以上代码在循环中运行,并且每次input_txt的大小不同时(例如,可能需要增大到input_txt [14]或更大。我如何动态构建上述命令,以便每次具有所需的命令时) input_txt条目数?
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. 一种想法是尝试使用字符串操作来构建命令,然后使用'exec'来运行它,但是我该怎么做呢?...最重要的是换行符'\\ n'似乎使事情变得复杂。 Any help will be greatly appreciated.
任何帮助将不胜感激。 Many thanks!
非常感谢!
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. 这将连接
input_txt
的条目,用“ \\ n”分隔它们,并在末尾附加一个尾随的“ \\ n”。
You can then use: 然后,您可以使用:
data_out = p.communicate(input_str)[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.