python - 避免在 plumbum 中转义 glob 表达式

标签 python shell plumbum

假设我想使用 plumbum 运行类似 ls a* 的程序.

from plumbum.cmd import ls
ls['a*']()
...
ProcessExecutionError: Command line: ['/bin/ls', 'a*']
Exit code: 1
Stderr:  | ls: a*: No such file or directory

我知道 plumbum 会自动转义参数,这通常是件好事。但是有没有办法让它理解 glob 表达式应该按原样传递给 shell?

最佳答案

But is there a way to make it understand glob expressions should be passed to the shell as-is?

plumbum 按原样将 a* 传递给 ls 命令。 ls 命令不运行任何 shell,因此没有 glob 扩展(它由 *nix 上的 shell 完成)。

您可以使用 glob 模块来进行扩展:

from glob import glob

ls('-l', *glob('a*'))

另一种方法是使用 Workdir 对象:

from plumbum import local

ls('-l', *local.cwd // 'a*')

延迟调用;您可以使用 ls['-l'][args] 语法(注意:plumbum 1.1.0 版本中可能存在一个错误,需要转换 args 明确地列出一个元组)。

如果你愿意;你可以调用 shell:

from plumbum.cmd import sh

sh('-c', 'ls -l a*')

注意:Python 的 glob.glob() 函数可能产生与 shell 不同的 glob 扩展。

关于python - 避免在 plumbum 中转义 glob 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15730126/

相关文章:

python - 选择要训练的层并在 Keras 中训练的 Inception 模型中添加跳过连接

python - 需要接受隐私政策才能访问页面

python - 同时迭代多个列表并捕获值的差异

shell - 将 grep 过滤器的输出附加到文件

python - Kaggle Opencv 重启 Notebook

linux - 有没有办法告诉 sed 忽略符号链接(symbolic link)?

linux - 使用 LFTP 回显当前文件传输

python - Fabric vs Plumbum : differences, 用例、优缺点

python 铅 : Passing $ in an cmd argument

python - Plumbum - 嵌套 SSH 远程处理/跳转主机