[英]Avoid escaping glob expressions in plumbum
Suppose I want to run something like ls a*
using 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
I understand plumbum automatically escapes the arguments, which is usually a good thing. 我知道plumbum会自动逃避参数,这通常是一件好事。 But is there a way to make it understand glob expressions should be passed to the shell as-is?
但有没有办法让它理解glob表达式应该按原样传递给shell?
But is there a way to make it understand glob expressions should be passed to the shell as-is?
但有没有办法让它理解glob表达式应该按原样传递给shell?
plumbum
passes a*
to ls
command as-is. plumbum
按原样传递a*
到ls
命令。 ls
command doesn't run any shell, so there is no glob expansion (it is done by the shell on *nix). ls
命令不运行任何shell,因此没有全局扩展(由* nix上的shell完成)。
You could use glob
module to do the expansion: 您可以使用
glob
模块进行扩展:
from glob import glob
ls('-l', *glob('a*'))
Another way is to use Workdir
object: 另一种方法是使用
Workdir
对象:
from plumbum import local
ls('-l', *local.cwd // 'a*')
To defer the call; 推迟通话; you could use
ls['-l'][args]
syntax (note: there is probably a bug in plumbum 1.1.0
version that requires to convert args
list to a tuple explicitly). 你可以使用
ls['-l'][args]
语法(注意: plumbum 1.1.0
版本中可能存在一个错误,需要将args
列表显式转换为元组)。
If you want; 如果你想; you could call the shell:
你可以调用shell:
from plumbum.cmd import sh
sh('-c', 'ls -l a*')
Note: Python's glob.glob()
function might produce the glob expansion different from that of the shell. 注意:Python的
glob.glob()
函数可能会产生与shell不同的glob扩展。
You can do your own glob expansion using Python's builtin glob
module . 你可以使用Python的内置
glob
模块进行自己的glob扩展。 For your example: 对于你的例子:
from plumbum.cmd import ls
from glob import glob
ls[glob('a*')]
For the special case of ls, there's another way: 对于ls的特殊情况,还有另一种方法:
from plumbum import local
p = local.path('path/to/dir')
local.cwd.glob(str(p) + 'a*')
-- or -- - 要么 -
from plumbum import local
p = local.path('path/to/dir')
local.cwd.chdir(p)
local.cwd.glob('a*')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.