fla*_*nco 1 python terminal python-2.7
有人可以帮助理解终端窗口中的打印是如何工作的吗?这是一个测试脚本
test_script.py
import telnetlib
HOST = "10.1.1.151"
tn = telnetlib.Telnet(HOST)
tn.open(HOST)
test_var = ["test"]
print test_var
tn_read = tn.read_very_eager()
print tn_read
Run Code Online (Sandbox Code Playgroud)
脚本从终端运行时的输出:
$ python test_script.py
['test']
Run Code Online (Sandbox Code Playgroud)
tn_read 应该是类似"用户名:"但它不会打印在终端窗口中.
如果我从解释器运行它,我会得到预期的结果:
>>> tn.read_very_eager()
'\n\rUser Name : '
Run Code Online (Sandbox Code Playgroud)
从终端调用脚本时,为什么或需要做什么来获得以下输出?
$ python test_script.py
['test']
User Name :
Run Code Online (Sandbox Code Playgroud)
简短的回答是使用read_until()超时.例如
timeout = 3 # seconds
tn_read = tn.read_until('User Name :', timeout)
print repr(tn_read)
Run Code Online (Sandbox Code Playgroud)
答案如下.
read_very_eager()是非阻塞的,它将返回已经可用的任何已烹饪数据,但如果没有任何数据则不返回任何数据.如果在建立连接后过快地调用非阻塞"读取"方法,则可能没有要读取的数据并且read_very_eager()将返回空字符串 - ''.
所以你的问题可能与时间有关; 读取是非阻塞的,不能返回尚未接收,处理和缓冲的数据.当您通过终端进行交互时,您需要时间输入命令,因此您不会注意到计时问题,但是从脚本运行时,人为延迟将被删除,并且计时问题将变得明显.在调用read方法之前尝试睡眠:
import telnetlib
import time
HOST = "10.1.1.151"
tn = telnetlib.Telnet(HOST)
test_var = ["test"]
print test_var
time.sleep(5)
tn_read = tn.read_very_eager()
print repr(tn_read)
Run Code Online (Sandbox Code Playgroud)
将上面的内容作为脚本运行,您可能会看到预期的输出....然后,您可能不会.相反,您可能仍会看到:
['test']
''
Run Code Online (Sandbox Code Playgroud)
可能还有其他因素,特别是服务器可能正在使用Telnet IAC序列进行响应.telnetlib如果它在你调用之前到达read_very_eager()(实际上是任何读取函数),它将使用这个序列.在这种情况下,read_very_eager()还会返回一个空字符串.
如果您想查看通过连接进行的交换,可以致电set_debuglevel(1):
导入telnetlib
tn = telnetlib.Telnet('library.cedarville.edu') # any old server will do
tn.set_debuglevel(1)
tn_read = tn.read_all()
print repr(tn_read)
Run Code Online (Sandbox Code Playgroud)
典型输出是:
Telnet(library.cedarville.edu,23): recv '\xff\xfd\x03'
Telnet(library.cedarville.edu,23): IAC DO 3
Telnet(library.cedarville.edu,23): recv '\xff\xfb\x03\xff\xfb\x01\xff\xfd\x18\xff\xfd#\xff\xfd$\xff\xfd\x1f'
Telnet(library.cedarville.edu,23): IAC WILL 3
Telnet(library.cedarville.edu,23): IAC WILL 1
Telnet(library.cedarville.edu,23): IAC DO 24
Telnet(library.cedarville.edu,23): IAC DO 35
Telnet(library.cedarville.edu,23): IAC DO 36
Telnet(library.cedarville.edu,23): IAC DO 31
Telnet(library.cedarville.edu,23): recv '\r\n'
Telnet(library.cedarville.edu,23): recv 'login: '
Run Code Online (Sandbox Code Playgroud)
在其他"读取"函数中,您应该使用read_until().如果您不想无限期阻止,请向其传递超时,如上所示.