Popen.stdin.write不适用于Python3

时间:2019-10-12 15:54:38

标签: python python-3.x subprocess

Popen.stdin.write不适用于Python3

我正在启动与远程设备的telnet连接,并开始发送命令。 下面是一个简单的示例,该示例通过telnet连接到远程设备并开始发送设备特定命令[即“ vr”,“ KP开启”]


import subprocess

telnet_client = subprocess.Popen(
    ["telnet", "192.168.1.120", "4002"],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    universal_newlines=True)

#Get Version
telnet_client.stdin.write('vr\n')
telnet_client.stdin.flush()

#Power on the device
telnet_client.stdin.write('kp on\n')
telnet_client.stdin.flush()

#Factory default
telnet_client.stdin.write('fd\n')
telnet_client.stdin.flush

每个stdin.write()都不会引发任何异常或错误,只是返回写入的字节数。但是实际上消息没有发送。

Ubuntu机器1:

我观察到在机器上安装Python3后,上述实现停止了与Python2.7的配合

Ubuntu机器2:

在安装Python3之后的另一台Ubuntu计算机中,以上实现适用于Python2.7,但不适用于Python3。

很普遍,在任何方向Popen.stdin.write都不适用于Python3。我相信某些软件包正在使系统陷入困境。

请让我知道这一点

2 个答案:

答案 0 :(得分:0)

我面临着同样的问题。 process.stdin.write()在Python 2.7中有效,但在Python 3中无效。尽管我无法调试问题所在,但是我可以使用process.communicate()实现该功能。 Documentation。这是与流程进行通信的推荐方式。另外,我们传递给此方法的输入字符串必须以'\n'结尾。

答案 1 :(得分:0)

这一切都准备好了。

实际上,服务器在调用stdin.flush之后正在接收数据

telnet_client.stdin.write('vr\n')
telnet_client.stdin.flush()