如何将星号传递给 python 中的模块 "sh"?

How to pass an asterisk to module "sh" in python?

我在 python 中使用 "sh" 模块以便在 Linux 上调用外部命令。在我的特定情况下,我想调用 "du" 命令,因为它比进行此类计算 "by hand" 更有效。不幸的是,以下行不起作用:

output = sh.du('-sx', '/tmp/*')

但这确实有效:

output = sh.du('-sx', '/tmp/')

如果我传递星号,我会收到以下错误消息:

'ascii' codec can't encode character u'\u2018' in position 87: ordinal not in range(128)

有谁知道如何处理命令行参数中的星号?


根据要求,这里是堆栈跟踪:

Traceback (most recent call last):
  File "./unittest.py", line 33, in <module>
    output = sh.du('-sx', '/tmp/*')
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 1021, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 486, in __init__
    self.wait()
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 500, in wait
    self.handle_command_exit_code(exit_code)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 516, in handle_command_exit_code
    raise exc(self.ran, self.process.stdout, self.process.stderr)
sh.ErrorReturnCode_1

使用sh.glob

sh.du('-sx', sh.glob('/tmp/*'))

答案是:

我忘了星号处理是由 bash 自己完成的,而不是由 "du" 完成的。这意味着:"sh" 的行为确实正确且完全符合预期。它将“/tmp/*”直接传递给 "du"(但 bash 不会)。这就是 Padraic Cunningham 试图告诉我的。

因此,做我想做的事情的唯一正确方法是用户 rmn 描述的方式:

sh.du('-sx', sh.glob('/tmp/*'))

这正是 bash shell 在调用 "du".

时本身所做的