将任意数量的输入从 python 发送到 .exe
p = subprocess.Popen(args = "myprog.exe" + " " +
str(input1) + " " +
str(input2) + " " +
str(input3) + " " +
strpoints, stdout = subprocess.PIPE)
在上面的代码中,input1、input2 和 input3 都是转换为字符串的整数。变量“strpoints”是任意长度字符串的列表。 input1 告诉 myprog strpoints 的长度。当然,当我尝试运行上面的代码时,我收到以下错误消息:
类型错误:无法将“列表”对象隐式转换为 str
我如何将 strpoints 的所有元素传递给 myprog.exe?我是否注定要执行 str(strpoints) 然后让 myprog.exe 解析它以获取逗号、撇号等?例如,
`>> x = ['a', 'b']
``>> str(x)
“['a','b']”
或者我应该提前创建一个巨大的字符串?例如,
'>>> x = ['a', 'b']
'>>>字符串化(x)
'a b'
其中 stringify 类似于
def stringify(strlist):
rlist = ""
for i in strlist:
rlist = rlist + i + " "
return rlist
p = subprocess.Popen(args = "myprog.exe" + " " +
str(input1) + " " +
str(input2) + " " +
str(input3) + " " +
strpoints, stdout = subprocess.PIPE)
in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable "strpoints" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message:
TypeError: Can't convert 'list' object to str implicitly
how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g.,
`>>> x = ['a', 'b']
`>>> str(x)
"['a', 'b']"
or should i create a huge string in advance? e.g.,
'>>> x = ['a', 'b']
'>>> stringify(x)
' a b'
where stringify would be something like
def stringify(strlist):
rlist = ""
for i in strlist:
rlist = rlist + i + " "
return rlist
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
args 可以是一个序列:
如果您的参数包含 shell 元字符(例如 ' *)并且您不希望将它们解释为这样,则这是更正确的。
args can be a sequence:
This is more correct if your arguments contain shell metacharacters e.g. ' * and you don't want them interpreted as such.
尝试使用 string.join:
Try using string.join:
避免使用该字符串将所有参数连接到一个字符串中。
仅传递参数序列(列表或元组)要简单、更好、更安全。如果任何参数包含空格字符(这对于文件名来说很常见),则尤其如此。
Avoid concatenating all arguments into one string using that string.
It's a lot simpler and better and safer to just pass a sequence (list or tuple) of arguments. This is specially true if any argument contains a space character (which is quite common for filenames).
您是否想过将这些字符串括在引号中,以防它们嵌入空格?类似于:
这会使您的字符串更长,但会保留列表中各个元素的完整性。
Any thought that you might want to enclose those strings in quotes, in case they have embedded spaces? Something like:
This makes your string longer, but will preserve the integrity of your individual elements in the list.