2

我想在该用户的$SHELL. 该命令可能是短期的(如ls)或长期的(如firefox),它可能是单个命令、管道或任何其他 shell 支持的构造。

执行方法必须代表 shell 指示成功或失败,并且无论命令何时终止或是否终止,都不得阻塞。在执行方法返回并且我的程序继续之前,该命令可能永远不会终止。

Popen()withshell=True不会阻塞,但也不表示失败。辅助函数确实阻塞并且在subprocess这里没有用。Popen.poll()(在这个问题中建议)返回None直到命令终止并且不会立即返回非None失败(必须重复调用它直到 shell 终止)。

作为所需行为的示例

prog1 = shell_run('blocking_prog', stdin=PIPE, stdout=PIPE)
prog2 = shell_run('nonsense_prog', stdin=PIPE, stdout=PIPE)

第一行应该将一个Popen对象分配给prog1,第二行应该提出一个OSError或类似的。

我认为在这些条件下不可能可靠地检测到错误是正确的吗?Popen()

4

2 回答 2

1

我不会直接回答你的问题,但使用plumbum这些任务可以让你的生活变得更轻松。http://plumbum.readthedocs.org/en/latest/

于 2013-03-07T19:23:04.183 回答
0

如果您必须知道它是否失败才能知道是否输入数据,您可以这样做

prog2 = shell_run('nonsenseprog', stdin=PIPE, stdout=PIPE,
               shell=True, executable=os.getenv('SHELL'))
# If the program does not exist, it should fail immediately and .poll() knows about that.
# If it exists and runs, `.poll()` returns None.
if prog2.poll() is not None:
    raise Whatever # it failed

或者,您可以检查您是否真的需要shell=True.

于 2013-08-16T07:06:43.140 回答