Why the command cannot be executed normally after Python IDLE reload (sys)
Generally, most people ExecuteReload (sys)This statement is only used to modify the default Character Set of Python, that is, to callSys. setdefaultencoding (). However, if you executeReload (sys), And the subsequent commands cannot be executed normally.
I was helpless when I first encountered this problem. Later I accidentally saw someone talking about this problem on stackoverflow. It turns out that IDLE is used as a GUI Shell environment. during initialization, specific standard input, standard output, and standard error output are set, so that the input and output are both in the idle gui Shell. You can view them in IDLE as follows:
>>> import sys>>> print sys.stdin
>>> print sys.stdout
>>> print sys.stderr
>>>
If you manually executeReload (sys)Later,SysThe three variables of the module will be reset, and the output cannot be displayed in IDLE. Therefore, the solution is simple.ReloadCopy all three variables,ReloadThen you can restore it:
>>> stdi,stdo,stde=sys.stdin,sys.stdout,sys.stderr>>> reload(sys)>>> sys.stdin,sys.stdout,sys.stderr=stdi,stdo,stde>>> print sys.stdout
>>>
Careful people may think,Reload (sys)If the standard input, standard output, and standard error output do not workRelaod (sys)Next sentenceSys. stdin, sys. stdout, sys. stderr = stdi, stdo, stdeHow can it be executed? So in factReload (sys)After and before the restoration, the standard input can still work normally. You can test it using the following code:
>>> reload(sys)>>> sys.stdout=stdo>>> print sys.stdin
', mode 'r' at 0x0000000001CAB030>>>> print sys.stdout
>>> print sys.stderr
', mode 'w' at 0x0000000001CAB150>>>>
The problem is solved, but it must be emphasized that:
Never use reload (sys) easily unless you completely clear the results! It is unwise to execute reload (sys) just to be able to reset the Python default encoding!
The Python designer deliberately deletes the object after Python Initialization is complete.SysModuleSetdefaultencoding ()To avoid any unknown problems. In fact, there are other more reliable solutions to the coding problem.