How to pass an asterisk to module “sh” in python?

柔情痞子 提交于 2019-12-23 00:51:01

问题


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/*')

But this does work:

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)

Does anyone know how to deal with asterisks in command line arguments?


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

回答1:


The answer is:

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.

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/*'))

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




回答2:


use sh.glob

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


来源:https://stackoverflow.com/questions/32923189/how-to-pass-an-asterisk-to-module-sh-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!