Python telnet works in command line but not in script

耗尽温柔 提交于 2019-12-12 03:45:21

问题


I'm writing a python script to automatically close an Android Emulator. I used to work on a Linux environments but I'm now migrating the code to Windows. Problem is,

$ adb emu kill

Doesn't work on Windows so I resort to making a python script that telnets to the emulator and kills the emulator. Here's the code:

import telnetlib
host = "localhost"
port = "5554"

tn = telnetlib.Telnet(host,port)
tn.write("kill\n")
tn.close()

The problem that I encountered with this is that it doesn't work when I try running this code when I enter

python killEmulator.py

with "killEmulator.py" being the filename of the code.

BUT when I enter the lines of this file one by one on the command line, it works and manages to kill the emulator.

import telnetlib
host = "localhost"
port = "5554"
tn = telnetlib.Telnet(host,port)
tn.write("kill\n")
tn.close()

When I do it like this, it works perfect. Can anyone tell what's going on?


回答1:


I don't know the details here, but when you open a Telnet session the server needs to start a new shell process, and probably can't accept any data until after the shell has been started, depending on the server implementation.

A simple fix for your problem is to just add time.sleep(0.5) before tn.write("kill\n"), giving the server half a second to get ready. A more elegant way would be to wait for the prompt before writing anything, like this:

r = tn.read_until("$ ", 5)
assert "$ " in r, "Timeout waiting for prompt!"
tn.write("kill\n")


来源:https://stackoverflow.com/questions/15022848/python-telnet-works-in-command-line-but-not-in-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!