[英]Python telnet works in command line but not in script
I'm writing a python script to automatically close an Android Emulator. 我正在编写python脚本以自动关闭Android模拟器。 I used to work on a Linux environments but I'm now migrating the code to Windows. 我曾经在Linux环境下工作,但现在将代码迁移到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. 在Windows上不起作用,所以我求助于制作一个python脚本,该telnet连接到仿真器并杀死该仿真器。 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
with "killEmulator.py" being the filename of the code. 其中“ killEmulator.py”是代码的文件名。
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? 谁能告诉我发生了什么事?
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. 我不知道这里的详细信息,但是当您打开Telnet会话时,服务器需要启动一个新的Shell进程,并且可能在启动Shell之后才接受任何数据,具体取决于服务器的实现。
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. 解决您的问题的简单方法是,在tn.write("kill\\n")
之前添加tn.write("kill\\n")
time.sleep(0.5)
tn.write("kill\\n")
,使服务器有半秒钟的准备时间。 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.