Disable automatic printing in Python interactive session

筅森魡賤 提交于 2019-12-24 09:57:14

问题


I am going to be holding a Python workshop to teach some beginner level programmers at my college Python.

I am looking for a way to modify the default behavior of Python interactive sessions so that expressions do not automatically print out results. For example, take this following interactive session:

wil@calcifer:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 5
>>> y = 7
>>> x + y
12
>>> first_name = "Test"
>>> last_name = "Person"
>>> first_name + last_name
'TestPerson'
>>>

This would enforce the use of the print statement to avoid confusion later on. This isn't crucial, but I was surprised that I was unable to find any settings for this anywhere.

I would be able to preconfigure the machine beforehand, so any solutions would work. Does anyone know if this is possible, or what change to the interactive sessions creates this effect?


回答1:


I know you didn't come here for teaching advice, but without an output, what's x + y supposed to do? Why type it at all if you don't want the value to be output or stored anywhere?

Your students will be confused: "what does x + y do?"

If you want to show some expression, just consistently put a print statement in front of it, or assign it to a value.

I've found that people are often confused the other way around, so much that they don't know that return actually gives them the value back, and they always want to use print. Don't forget that you can define functions interactively, and put the return there. Then you can show them that the function returns that value, even with no prints.




回答2:


The expression printing in interactive sessions is mediated via a call to sys.displayhook. Just override it to a NOP:

>>> import sys
>>> sys.displayhook = lambda x: None

>>> 2 + 3
>>> print 2 + 3
5
>>> 

In a plain Python session it is wired to sys.stdout. Applications that offer a Python shell on a GUI are expcted to use it to print the expression values back to the user.

You can write your pythonrc.py ( ~/.pythonrc.py file) to do this by default, each time the interpreter is called. Further documentation on sys.displayhook can be found here: http://docs.python.org/3/library/sys.html#sys.displayhook




回答3:


I don't think you can configure the shell to suppress the results of expressions, but would it work if you just assigned every expression to a variable? It won't print anything then...

E.G.

x=5
y=7
z = x+y


来源:https://stackoverflow.com/questions/15534880/disable-automatic-printing-in-python-interactive-session

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