如何将星号传递给模块“ sh”?在python中? [英] How to pass an asterisk to module "sh" in python?

查看:87
本文介绍了如何将星号传递给模块“ sh”?在python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python中使用 sh模块,以便在Linux上调用外部命令。在我的特殊情况下,我想调用 du命令,因为它比手动执行这种计算更为有效。不幸的是,以下行不起作用:

I'm using the "sh" module in python in order to call external commands on Linux. In my particular case I would like to call the "du" command because it is more efficient than doing such calculations "by hand". Unfortunately the following line does not work:

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

但这确实有效:

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

如果通过星号,则会收到以下错误消息:

If I pass an asterisk I get the following error message:

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

有人知道如何

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

As requested, here is the stack trace:

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


推荐答案

答案是:

我忘记了星号处理是由bash本身完成的,而不是由 du完成的。这意味着: sh的行为确实正确且完全符合人们的预期。它直接将 / tmp / *传递给 du(但bash不会)。这就是Padraic Cunningham想要告诉我的。

I forgot that asterisk processing is done by bash itself, not by "du". Which means: "sh" indeed behaves correcly and exactly as one should expect. It passes "/tmp/*" directly to "du" (but bash does not). That's what Padraic Cunningham tried to tell me.

因此,唯一有效的方法就是用户rmn描述的方法:

Therefor the ONLY correct way to do what I'm trying to do is the way the user rmn described:

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

这正是bash shell本身在调用 du时所做的事情。

And this is exactly what the bash shell itself does when calling "du".

这篇关于如何将星号传递给模块“ sh”?在python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆