Skip to main content
 首页 » 编程设计

python之如何为 subprocess.call 模拟 sys.stdout (err, in)

2024年10月01日8zengkefu

我想捕获和分析执行此操作的函数的输出:

subprocess.call(args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)

当我在 py.test 下运行没有任何模拟的代码时,我得到错误:ValueError: redirected Stdin is pseudofile, has no fileno()

当我用 mock 修补 sys.stdin(和其他)时,我得到了同样的错误。

当我使用 mock.mock_open() 修补 sys.stdin 时,出现错误:AttributeError: Mock object has no attribute 'write'

当我使用 mock.mock_open()('name', 'r') 修补 sys.stdin 时,我收到初始错误:ValueError: redirected Stdin is pseudofile, has no fileno( )

有没有办法将某种模拟对象作为子进程的标准输入/输出传递?

我想要这样的东西:

mocked = (put something here) 
subprocess_call('ls', stdin=mocked, stdout=mocked, stderr=mocked) 

在 py.test 下运行时应该可以工作。

谢谢。

请您参考如下方法:

经过一番努力,我找到了一种方法来修补和拦截 subprocess.call 的标准输出。

我的主要问题是 call 函数的非模拟版本需要来自操作系统的实际文件描述符 (FD)。没有模拟能够为我提供这样的东西。

与此同时,我真的想避免创建任何文件,因为它确实会使测试的设置/拆卸复杂化。我决定使用 os.pipe 调用来创建 FD,并将它们用于 subprocess.call

的标准输出捕获

这里是我测试的简化版本:

def test_exec_results(ssh): 
    rfd, wfd = os.pipe() 
    w = os.fdopen(wfd, 'w', 0) 
    with mock.patch.multiple(app.sys, stdout=w, stderr=w, stdin=None): 
        app.myfunction('test message') 
    output = os.read(rfd, 1000) 
    assert 'test message ' in output 
    assert 'some_other_things' in output