Python脚本输出与Python控制台输出的区别

0 投票
2 回答
1441 浏览
提问于 2025-04-17 10:01

我有一个 .py 文件:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file.  Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close()

我不明白的地方:

a) 为什么在解释器里,如果我输入 raw_input("?"),然后输入 f 并按回车,它会输出 'f' 字符串,而如果我运行这个 .py 文件却没有返回 'f' 字符串呢?

b) 另外,Python 的文档说:“这个函数会从输入中读取一行,转换成字符串(去掉末尾的换行符),然后返回这个字符串。”那么,为什么第 7 行会在新的一行打印,而不是在第 6 行(“?打开文件...”)的后面?那个 \n 是从哪里来的呢?

2 个回答

0

a) 它确实返回了字符串,但你没有把它保存到一个变量里。在这种情况下,交互式解释器会显示这个值。

b) \n 可能是你输入的一部分(你打的内容),不过很难确切知道你想表达的是什么。

0

a) 默认情况下,解释器会打印出命令的输出,但你的脚本不会这样做,除非你使用了 print 语句。

print raw_input('?')

b) 从 raw_input 返回的字符串中并没有包含 '\n',但是当你按下回车键时,控制台会捕捉到这个换行符,所以这就是使用 raw_input 时的一个副作用。

print repr(raw_input('?'))  # You'll get 'f', not 'f\n'

撰写回答