【问题标题】:Python subprocess Popen: Why does "ls *.txt" not work? [duplicate]Python 子进程 Popen:为什么“ls *.txt”不起作用? [复制]
【发布时间】:2012-12-02 07:04:56
【问题描述】:

我在看this 问题。

就我而言,我想做一个:

import subprocess
p = subprocess.Popen(['ls', 'folder/*.txt'], stdout=subprocess.PIPE, 
                                 stderr=subprocess.PIPE)

out, err = p.communicate()

现在我可以在命令行上检查执行“ls 文件夹/*.txt”是否有效,因为该文件夹有许多 .txt 文件。

但在 Python (2.6) 中我得到:

ls: 无法访问 * : 没有这样的文件或目录

我尝试过这样做: r'folder/\*.txt' r"folder/\*.txt" r'folder/\\*.txt' 和其他变体,但似乎Popen 根本不喜欢* 字符。

有没有其他方法可以逃脱*

【问题讨论】:

  • 逃脱它?我认为您想要的是先扩展“*”,然后运行 ​​ls 命令。阅读“外壳扩展”。

标签: python subprocess ls


【解决方案1】:

*.txt 会被您的 shell 自动扩展为 file1.txt file2.txt ...。如果引用*.txt,则不起作用:

[~] ls "*.py"                                                                  
ls: cannot access *.py: No such file or directory
[~] ls *.py                                                                    
file1.py  file2.py file3.py

如果您想获取与您的模式匹配的文件,请使用glob

>>> import glob
>>> glob.glob('/etc/r*.conf')
['/etc/request-key.conf', '/etc/resolv.conf', '/etc/rc.conf']

【讨论】:

  • 谢谢。在 Python 中使用 Popen 时,必须使用引号。请参阅链接的答案或 Python 文档。
  • @aaa:问题是你没有使用 shell,它不允许 globbing。用Popen 调用ls 不是一个好主意,IMO,因为 Python 提供了更好的工具。
  • 啊,现在我明白了。是的,你是对的,glob 是一个更好的库。看,我刚刚学到了一个新东西:)
【解决方案2】:

您可以将参数shell 传递给True。它将允许通配符。

import subprocess
p = subprocess.Popen('ls folder/*.txt',
                     shell=True,
                     stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
out, err = p.communicate()

【讨论】:

  • 是的,这行得通。我错误地认为 Popen 的参数必须排列,因为所有示例都是这样做的
  • p.communicate() 是一个阻塞调用,我们可以以非阻塞方式有相同的行为吗?谢谢
猜你喜欢
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多