plumbum.commands.processes.ProcessExecutionError:对于返回null的命令

时间:2018-09-01 14:13:03

标签: python plumbum

我要运行的shell命令,什么都不返回:

echo helloWorld | grep 'dummy'

铅字版本:

以下线路有效:

out=(echo["helloWorld"] | grep["h"])().strip()

但是下面一行没有,这可能是什么原因?

out=(echo["helloWorld"] | grep["dummy"])().strip()
print(out)

我遇到错误:

Traceback (most recent call last):
  File "dd.py", line 6, in <module>
    out=(echo["helloWorld"] | grep["dummy"])().strip()
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/commands/base.py", line 103, in __call__
    return self.run(args, **kwargs)[1]
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/commands/base.py", line 240, in run
    return p.run()
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/commands/base.py", line 201, in runner
    return run_proc(p, retcode, timeout)
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/commands/processes.py", line 232, in run_proc
    return _check_process(proc, retcode, timeout, stdout, stderr)
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/commands/processes.py", line 23, in _check_process
    proc.verify(retcode, timeout, stdout, stderr)
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/commands/base.py", line 412, in verify
    dstproc_verify(retcode, timeout, stdout, stderr)
  File "/home/user/venv/lib/python3.5/site-packages/plumbum/machines/base.py", line 26, in verify
    stderr)
plumbum.commands.processes.ProcessExecutionError: Command line: ['/bin/grep', 'dummy']
Exit code: 1

[Q] 如何解决此错误?

1 个答案:

答案 0 :(得分:1)

之所以会发生这种情况,是因为grep的退出状态为1(如果找不到任何内容),如its manual

中所述

如果愿意,可以在命令行中尝试它:

echo helloWorld | grep h; echo $?
echo helloWorld | grep x; echo $?

会导致

helloWorld
0
1

另一种nice answer(例如,

echo helloWorld | grep x | cat

将产生0作为状态。但是不幸的是,铅锤使用局部管道机制,因此grep输出进入铅锤,然后铅锤将其输送到下一个命令-这意味着猫无法吞下退出代码1,在它之前会抛出异常。

因此,我的两个想法是创建一个shell脚本来运行grep,而不会在没有结果的搜索中返回错误:

#!/bin/bash
grep "$@" || test $? = 1

执行此操作而不是grep(在原始答案中称为c1grep),或者在管道代码周围添加try / except块并手动处理退出代码1(ProcessExecutionError)。