In the python 2.7 shell, after I do the following:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
the shell stop showing the result. If I type print('hello world'), nothing is shown.
By the way, why reload(sys) is essential here? Without it the setdefaultencoding() cause an error?
The question about needing reload(sys) has nothing to do with IDLE. Read the last sentence of the 2.7 doc entry.
sys.setdefaultencoding(name)
Set the current default string encoding used by the Unicode implementation.
If name does not match any available encoding,
LookupError is raised. This function is only intended to be used by
the site module implementation and, where needed, by sitecustomize.
Once used by the site module, it is removed from the sys module’s
namespace.
You are not supposed to use the function. In 3.x, it has been removed (or made invisible). Hence the following from the standard Python console interpreter.
C:\Users\Terry>py
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys
<module 'sys' (built-in)>
>>> sys.setdefaultencoding
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'setdefaultencoding'
In 2.7, reload re-initializes the module, undoing the removal. Hence
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding
<built-in function setdefaultencoding>
EDIT: Irrelevant material removed and the following correct answer added.
As to the print problem: reload also undoes IDLE's modification of the output streams. This disables print commands. They execute (don't raise) but nothing is actually sent.
>>> print 'abc', u'abc'
>>>
The above is after reload but before calling the revived setdefaultencoding. I plan to add a note to the IDLE doc warning that reloading sys disables IDLE by undoing its modifications thereof.
Related
In Python 2.7 I have the following and I debug through IDLE:
print 'Here'
import sys
reload(sys)
sys.setdefaultencoding('cp1252')
print 'There'
what I get in return is
Here
So after I have set the default encoding it does not print the desired output.
Could this be due by conflicts with the IDLE encoding?
Because it is unable to find reference to setdefaultencoding from sys. That is why it is not printing 'There'
setdefaultencoding is deprecated and one should never use it!
Have a look at the following link.
Why should we NOT use sys.setdefaultencoding(“utf-8”) in a py script?
I'm taking a course in Python, and the current assignment is to convert a previous assignment written in Python 2 (which used wxPython) to Python 3 (which needs Phoenix). I successfully installed Phoenix, and in the Py3 shell I can now import wx just fine. However, if I try to run my actually script, it immediately gets this error:
Traceback (most recent call last):
File "C:\Python27\transferdrillPy3.py", line 10, in
class windowClass(wx.Frame):
NameError: name 'wx' is not defined
What's up with that?
I tried going through my code and deleting every single "wx.", and now it works. I guess Phoenix doesn't need that.
This question already has answers here:
IPython Notebook locale error [duplicate]
(4 answers)
Closed 6 years ago.
After updating IPython I constantly have problems with matplotlib. At the beginning of my notebook I have
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import scipy
from qutip import *
import time
Which generate a screen full of issues but the final part is
/Users/murray/anaconda/lib/python2.7/locale.pyc in _parse_localename(localename)
473 elif code == 'C':
474 return None, None
--> 475 raise ValueError, 'unknown locale: %s' % localename
476
477 def _build_localename(localetuple):
ValueError: unknown locale: UTF-8
There were other issues before this which I managed to fix. Similar things have been reported here but no solution which works for me. One solution I found online suggested running
export LANG="it_IT.UTF-8"
in the terminal window (plus about 8 other similar commands). This worked but everytime I restart the notebook I have to reenter all of this. As you might guess I am not an expert - I would assume there is a more permanent fix for this problem
As a work around, you can put export LANG="it_IT.UTF-8" and the "8 other similar commands" into your .profile (assuming your are on Mac OS X).
At the end of this file /Users/murray/.profile write:
# Fix for matplotlib imports in IPython
export LANG="it_IT.UTF-8"
# your other 8 lines here without the # in front
You need to start a new terminal window. In there, start a new IPython session.
I am trying to use Stanford POS Tagger in NLTK but I am not able to run the example code given here http://www.nltk.org/api/nltk.tag.html#module-nltk.tag.stanford
import nltk
from nltk.tag.stanford import POSTagger
st = POSTagger(r'english-bidirectional-distim.tagger',r'D:/stanford-postagger/stanford-postagger.jar')
st.tag('What is the airspeed of an unladen swallow?'.split())
I have already added environment variables as
CLASSPATH = D:/stanford-postagger/stanford-postagger.jar
STANFORD_MODELS = D:/stanford-postagger/models/
Here is the error I keep getting
Traceback (most recent call last):
File "D:\pos_stanford.py", line 4, in <module>
st = POSTagger(r'english-bidirectional-distim.tagger',
r'D:/stanford-postagger/stanford-postagger.jar')
... LookupError: NLTK was unable to find the english-bidirectional-distim.tagger file! Use software specific configuration paramaters or set the STANFORD_MODELS environment variable.
Some forums suggest that
File "C:\Python27\lib\site-packages\nltk\tag\stanford.py", line 45, in __init__
env_vars=('STANFORD_MODELS'), verbose=verbose)
should be changed so that there is a comma in
env_vars=('STANFORD_MODELS',), verbose=verbose)
but it doesn't solve the problem either.
Please Help me in solving this issue.
Other Information:
I am using
Windows 7 64 bit
Python 2.7 32 bit
NLTK 2.0
Note : Just posting it as answer to help in case others face this issue in future
I finally found out what I did wrong.. it turned out to be a blunder.
Tagger file name is not 'english-bidirectional-distim.tagger'
but 'english-bidirectional-distsim.tagger'.
I have a Python module that is operating as a server for a wireless handheld computer. Every time the handheld sends a message to the server, the module determines what kind of message it is, and then assembles an appropriate response. Because the responses are often state-dependent, I am using global variables where needed to retain/share information between the individual functions that handle each type of message.
The problem I'm having is when the application is closed (for whatever reason), the global variable values are (of course) lost, so on re-launching the application it's out of synch with the handheld. I need a reliable way to store those values for recovery.
The direction I've gone so far (but have not gotten it to work yet) is to write the variable names and their values to a CSV file on the disk, every time they're updated -- and then (when the app is launched), look for that file and use it to assign the variables to their previous states. I have no trouble writing the file or reading it, but for some reason the values just aren't getting assigned.
I can post the code for comments/help, but before that I wanted to find out whether I'm just going an entirely wrong direction in the first place. Is there a better (or at least preferable) way to save and recover these values?
thanks,
JDM
====
Following up. It may be a touch klunky, but here's what I have and it's working. The only globals I care about are the ones that start with "CUR_". I had to use tempDict1 because the interpreter doesn't seem to like iterating directly over globals().
import pickle
CUR_GLO1 = 'valglo1'
CUR_GLO2 = 'valglo2'
CUR_GLO3 = 'valglo3'
def saveGlobs():
tempDict1 = globals().copy()
tempDict2 = {}
for key in tempDict1:
if (key[:4]=='CUR_'):tempDict2[key] = tempDict1[key]
pickle.dump(tempDict2,open('tempDict.p','wb'))
def retrieveGlobs():
tempDict = pickle.load(open('tempDict.p','rb'))
globals().update(tempDict)
writing it up as an answer..
What I think you want to do is a form of application checkpointing.
You can use the Pickle module for conveniently saving and loading Python variables. Here is a simple example of how to use it. This discussion on Stackoverflow and this note seem to agree, although part of me thinks that there must be a better way.
Incidentally, you don't need to put everything into a dictionary. As long as you dump and load variables in the right order, and make sure that you don't change that, insert data in the middle etc, you can just dump and load several variables. Using a dictionary like you did does remove the ordering dependency though.
% python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> foo=123
>>> bar="hello"
>>> d={'abc': 123, 'def': 456}
>>> f=open('p.pickle', 'wb')
>>> pickle.dump(foo, f)
>>> pickle.dump(bar, f)
>>> pickle.dump(d, f)
>>> ^D
% python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f=open('p.pickle','rb')
>>> foo=pickle.load(f)
>>> foo
123
>>> bar=pickle.load(f)
>>> bar
'hello'
>>> d=pickle.load(f)
>>> d
{'abc': 123, 'def': 456}
>>>