Difference between python script output and python console output

怎甘沉沦 提交于 2019-12-12 02:49:08

问题


I have this .py file:

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()

What I do not understand:

a) Why in the interpreter if I write, raw_input("?"), then type f and press enter, it outputs the 'f' string and if I run the .py file it doesn't return me the 'f' string?

b) Also, python docs says: " The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. So, why does the line 7 gets printed on a new line instead of line 6("?Opening the file..."). Where is that \n coming from?


回答1:


a) The interpreter prints the output of the commands by default, but your script doesn't do that unless you use the print statement.

print raw_input('?')

b) The '\n' isn't in the string returned from raw_input, but it's anyway captured by the console when you press enter so this is a side effect you get when using raw_input.

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



回答2:


a) It does return the string, but you're not saving it in a variable. The interactive interpreter will echo the value in that case.

b) The \n is probably part of the input (your typing), though it's hard to know what exactly you mean.



来源:https://stackoverflow.com/questions/8822117/difference-between-python-script-output-and-python-console-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!