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

2024-10-03 00:28:14 发布

您现在位置: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中的任何一个版本都可以得到我想要的答案。你知道吗


Tags: inpyhomelibpackagesshlinesite
1条回答
网友
1楼 · 发布于 2024-10-03 00:28:14

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

Glob expansion is a feature of a shell, like Bash, and is performed by the shell before passing the results to the program to be exec’d. Because sh is not a shell, but rather tool to execute programs directly, we do not handle glob expansion like a shell would.

So in order to use "*" like you would on the commandline, pass it into glob.glob() first:

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

相关问题 更多 >