python - 使用 split (' ' 拆分命令行是否有问题?

标签 python unix split

在大多数answers (我发现)对于问题“如何运行外部命令”我看到了一些内容

If you want to run ls -l you need to use subprocess.call(["ls", "-l"])

当我知道要运行的内容时,我通常会调用 subprocess.call('ls -l'.split(' ')) 以直观地显示命令行(通常是一个变量)。

与手动构建列表(同样,当命令已知时)相比,使用 split() 是否存在本质上的错误?或者这些答案是为了明确表明需要一个列表而设计的?

我试图找到一些缺点(多个空格、转义空格……),但我不知道这种方法会在哪里出错?

注意:这个问题具体是关于空间分割的稳健性,而不是安全问题或其他(非常重要)的考虑因素。

最佳答案

观察这是否有效:

>>> import subprocess
>>> subprocess.call(['ls', '-l', "my file"])
-rw-rw---- 1 john john 0 May  5 10:46 my file
0

但这并不:

>>> subprocess.call('ls -l "my file"'.split(' '))
ls: cannot access "my: No such file or directory
ls: cannot access file": No such file or directory
2

这确实有效:

>>> import shlex
>>> shlex.split('ls -l "my file"')
['ls', '-l', 'my file']
>>> subprocess.call(shlex.split('ls -l "my file"'))
-rw-rw---- 1 john john 0 May  5 10:46 my file
0

推荐

在Python哲学中,explicit is better than implicit 。因此,在这三种形式中,使用以下一种:

subprocess.call(['ls', '-l', 'my file'])

这避免了所有预处理,并清楚、明确地向您显示将要执行的内容及其参数。

关于python - 使用 split (' ' 拆分命令行是否有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37056950/

相关文章:

python - 分析多进程 Python 脚本时出现神秘的 pickle 错误

python - 模块未找到错误 : No module named 'torch.utils.serialization'

unix - 使用awk命令比较两个文件

r - 缩写科学名称的功能

python - 使用 JSON 和字典在 Python 中处理错误

python - 带有屏蔽数组的 KDTree

security - 通过SSH查找/替换根目录中的所有文件

pipe - 欺骗 Unix 命令行程序接受文件流

java - 使用 String.split(regex) 在空格和标点符号处拆分一行

Javascript/jQuery : Split camelcase string and add hyphen rather than space