“\r”在下面的脚本中做什么?

2024-05-15 15:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下脚本使用Telnet重新启动路由器:

#!/usr/bin/env python

import os
import telnetlib
from time import sleep

host = "192.168.1.1"
user = "USER"
password = "PASSWORD"
cmd = "system restart"

tn = telnetlib.Telnet(host)
sleep(1)

tn.read_until("Login: ")
tn.write(user + "\n\r")
sleep(1)

tn.read_until("Password: ")
tn.write(password + "\n\r")
sleep(1)

tn.write(cmd + "\n\r")

我不知道为什么,但是从上面的代码中删除“\r”会使脚本无法工作。那么“\r”在这个脚本中是做什么的?什么时候通常使用“\r”?

注:我知道“回车”这个词,但仍然不知道它在我的脚本中的用法。我在Linux中运行这个脚本。


Tags: import脚本cmdhostreadusr路由器sleep
3条回答

'\r'表示“回车”,与'\n'类似,后者表示“换行”或更常见的“换行”

在过去的打字机时代,你必须把写回线的托架移到线的开头,然后把线向下移动,才能写到下一行。

在现代计算机时代,由于多种原因,我们仍然拥有这种功能。但大多数情况下,我们只使用'\n',并自动假设我们希望从行的开头开始编写,因为否则就没有多大意义。

然而,有时我们只想使用'\r',如果我想写一些东西到一个输出,而不是去写一个新行,写一些别的东西,我想写一些东西在我已经写的上面,这是linux或windows命令行中有多少程序能够在同一行上更改“进度”信息。

现在大多数系统只使用'\n'来表示新行。但有些系统两者结合使用。

你可以在其他一些答案中看到这样的例子,但最常见的是:

  • 窗口以'\r\n'结尾
  • mac以^{结束行
  • unix/linux使用'\n'

其他一些程序也有特定的用途。

有关history of these characters的详细信息

\r是ASCIICarriage Return(CR)字符。

不同的操作系统使用不同的换行约定。最常见的是:

  • CR+LF(\r\n
  • 低频(\n
  • 铬(\r)。

\n\r(LF+CR)看起来很不传统。

编辑:我对Telnet RFC的阅读表明:

  1. CR+LF是telnet协议使用的标准换行序列。
  2. LF+CR是可接受的替代品:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

在网络虚拟终端会话中,'\r'字符是回车,回车换行对都是换行所必需的。


old telnet specification (RFC 854)(第11页):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

但是,在latest specification (RFC5198)(第13页)中:

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

因此,Telnet中的newline应该始终是'\r\n',但大多数实现要么没有更新,要么保留旧的'\n\r'以实现向后兼容性。

相关问题 更多 >