gpt4 book ai didi

Python:无法使用子进程模块在另一个命令行应用程序中读取/写入

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:31 24 4
gpt4 key购买 nike

我正在 Windows 中使用 Python 3.0 并尝试自动测试命令行应用程序。用户可以在被测应用程序中键入命令,它会以 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>

但是当我如下使用communicate()时,我得到了Sent数据包,但从未得到Recv:数据包。为什么我丢失了recv数据包?通信(0 应该从 stdout.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 中不起作用

最佳答案

这是一个常见的问题,例如请参阅:

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

我有两件事感兴趣:

  • p.stdin.write((command + '\r\n').encode()) 也是缓冲的,因此您的子进程甚至可能看不到它的输入。您可以尝试冲洗该管道。
  • 在其他问题之一中,有人建议对子项执行 stdout.read() 而不是 readline(),并读取适当数量的字符。您可能想尝试一下。

发布您的结果。

关于Python:无法使用子进程模块在另一个命令行应用程序中读取/写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1165064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com