1

我在 Windows 中使用 Python 3.0 并尝试自动化命令行应用程序的测试。用户可以在 Application Under Test 中键入命令,它会以 2 个 XML 数据包的形式返回输出。一个是包,另一个是包。通过分析这些数据包,我可以验证他的结果。我将代码如下

p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,

                   shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)

p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
testresult = p.stdout.readline()
testresult = testresult.decode()
print(testresult)

我无法返回任何输出。它卡在我尝试使用 readline() 读取输出的地方。我试过 read() 也卡住了

当我手动运行命令行应用程序并键入命令时,我将输出正确地作为两个 xml 数据包返回,如下所示

Sent: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\Python30\PyNTEST</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessagSent>

Recv: <PivotNetMessage>
<MessageId>16f8addf-d366-4031-b3d3-5593efb9f7dd</MessageId>
<ConversationId>373323be-31dd-4858-a7f9-37d97e36eb36</ConversationId>
<SageId>4e1e7c04-4cea-49b2-8af1-64d0f348e621</SagaId>
<SourcePath>C:\PivotNet\Endpoints\Pipeline\Pipeline_2.0.0.202</SourcePath>
<Command>echo</Command>
<Content>Hello</Content>
<Time>7/4/2009 11:16:41 PM</Time>
<ErrorCode>0</ErrorCode>
<ErrorInfo></ErrorInfo>
</PivotNetMessage>

但是当我使用如下的通信()时,我得到了 Sent 数据包并且永远不会得到 Recv: 数据包。为什么我错过了 recv 数据包?通信(0 应该从标准输出中带来一切。rt?

p = subprocess.Popen(SomeCmdAppl, stdout=subprocess.PIPE,

                   shell = True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write((command + '\r\n').encode())
time.sleep(2.5)
result = p.communicate()[0]
print(result)

任何人都可以帮助我提供应该工作的示例代码吗?我不知道是否需要在单独的线程中读写。请帮我。我需要重复读/写。我可以使用python中的任何高级模块吗?我认为 Pexpect 模块在 Windows 中不起作用

4

3 回答 3

1

这是一个流行的问题,例如参见:

(实际上,您应该在创建问题的过程中看到这些......?!)。

我有两件事感兴趣:

  • p.stdin.write((command + '\r\n').encode()) 也被缓冲,因此您的子进程甚至可能没有看到它的输入。您可以尝试冲洗此管道。
  • 在其他问题之一中,有人建议做一个标准输出。read()代替readline(),有适当数量的字符可供阅读。您可能想对此进行试验。

发布你的结果。

于 2009-07-22T13:52:50.637 回答
0

您是否考虑过使用 pexpect 而不是子进程?它处理可能阻止您的代码工作的细节(如刷新缓冲区等)。它可能还不适用于 Py3k,但它在 2.x 中运行良好。

见: http: //pexpect.sourceforge.net/pexpect.html

于 2009-09-04T03:49:19.770 回答
0

communicate尝试使用而不是使用发送您的输入write

result = p.communicate((command + '\r\n').encode())[0]
于 2009-07-22T13:04:56.253 回答