2024-09-25 00:32:01 发布
网友
我有一个参数列表,例如["hello", "bobbity bob", "bye"]。我该如何格式化这些文件,以便将它们适当地传递给shell?在
["hello", "bobbity bob", "bye"]
错误:
>>> " ".join(args) hello bobbity bob bye
正确:
您可以使用未记录但长稳定(至少since Oct 2004)subprocess.list2cmdline:
subprocess.list2cmdline
In [26]: import subprocess In [34]: args=["hello", "bobbity bob", "bye"] In [36]: subprocess.list2cmdline(args) Out[36]: 'hello "bobbity bob" bye'
解决问题的更简单的方法是在文本中至少有两个单词时添加“…\”。 为此:
# Update the list for str in args: if len(str.split(" ")) > 2: # Update the element within the list by # Adding at the beginning and at the end \" ... # Print args " ".join(args)
如果实际要将值发送到shell脚本,subprocess.popen将为您处理此问题:
subprocess.popen
http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen
否则,我相信你是在操纵琴弦。shlex.split所做的与您想要的相反,但似乎没有相反的结果。在
shlex.split
您可以使用未记录但长稳定(至少since Oct 2004)
subprocess.list2cmdline
:解决问题的更简单的方法是在文本中至少有两个单词时添加“…\”。
为此:
如果实际要将值发送到shell脚本,
subprocess.popen
将为您处理此问题:http://docs.python.org/library/subprocess.html?highlight=popen#subprocess.Popen
否则,我相信你是在操纵琴弦。
shlex.split
所做的与您想要的相反,但似乎没有相反的结果。在相关问题 更多 >
编程相关推荐