Python`sh`模块无法识别模式匹配

时间:2018-03-28 22:19:20

标签: python

出于某种原因,当我运行类似的东西时:

$ du -sh /some/regex.*/over?/here.txt

它给出正确答案,正确浏览子目录并返回答案。

奇怪的是,在python中使用sh模块,我运行相同的命令:

import sh
print(sh.du("-sh", "rsync_perf/d*/xa*"))

它给了我以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 1427, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 774, in __init__
    self.wait()
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 792, in wait
    self.handle_command_exit_code(exit_code)
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 815, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_1:

  RAN: /usr/bin/du -sh rsync_perf/d*/xa*

  STDOUT:


  STDERR:
/usr/bin/du: cannot access 'rsync_perf/d*/xa*': No such file or directory

它也不是相对与绝对路径问题:

print(sh.du("-sh", "/home/rzhang2/secdata/analysis/rsync_perf/d*/xa*"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 1427, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 774, in __init__
    self.wait()
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 792, in wait
    self.handle_command_exit_code(exit_code)
  File "/home/rzhang2/anaconda2/lib/python2.7/site-packages/sh.py", line 815, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_1:

  RAN: /usr/bin/du -sh /home/rzhang2/secdata/analysis/rsync_perf/d*/xa*

  STDOUT:


  STDERR:
/usr/bin/du: cannot access '/home/rzhang2/secdata/analysis/rsync_perf/d*/xa*': No such file or directory

注意:在同一目录中运行bash中的任一版本可以得到我想要的答案。

1 个答案:

答案 0 :(得分:3)

看看the documentation for this module,它并没有像bash那样声称支持bash风格的glob表达式。事实上,它根本不支持globs:

  

Glob扩展是shell的一个特性,比如Bash,并且在将结果传递给要执行的程序之前由shell执行。因为sh不是shell,而是直接执行程序的工具,所以我们不像shell那样处理glob扩展。

     

因此,为了像在命令行上一样使用"*",请先将其传递到glob.glob()

import sh
import glob
sh.ls(glob.glob("*.py"))