Python telnet 在命令行中工作但不在脚本中 [英] Python telnet works in command line but not in script
问题描述
我正在编写一个 python 脚本来自动关闭一个 Android 模拟器.我曾经在 Linux 环境中工作,但我现在正在将代码迁移到 Windows.问题是,
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
在 Windows 上不起作用,所以我求助于制作一个 python 脚本,该脚本 telnet 到模拟器并杀死模拟器.代码如下:
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
python killEmulator.py
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?
推荐答案
我不知道这里的细节,但是当您打开 Telnet 会话时,服务器需要启动一个新的 shell 进程,并且可能无法接受任何直到 shell 启动后的数据,具体取决于服务器实现.
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.
解决您的问题的一个简单方法是在 tn.write("kill\n")
之前添加 time.sleep(0.5)
,给服务器半个第二个准备.更优雅的方法是在写任何东西之前等待提示,如下所示:
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")
这篇关于Python telnet 在命令行中工作但不在脚本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!