Encoding of requirement file using pip - macos

On OSX (El Capitan, 10.11.6), using virtualenv (15.1.0), I am getting an error when installing requirements from a text file with pip (9.0.1):
virtualenv env
source env/bin/activate
pip install -r requirements.txt
but not when looping over each requirement manually:
for r in $(cat requirements.txt); do pip install "$r"; done
This makes me think there might be an issue with the default encoding assumed by pip when reading the requirements file. Is there a way (environment variable, I presume) to set the default encoding of requirement files?
The error I get is:
Exception:
Traceback (most recent call last):
File "/path/to/env/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/path/to/env/lib/python2.7/site-packages/pip/commands/install.py", line 312, in run
wheel_cache
File "/path/to/env/lib/python2.7/site-packages/pip/basecommand.py", line 295, in populate_requirement_set
wheel_cache=wheel_cache):
File "/path/to/env/lib/python2.7/site-packages/pip/req/req_file.py", line 84, in parse_requirements
filename, comes_from=comes_from, session=session
File "/path/to/env/lib/python2.7/site-packages/pip/download.py", line 422, in get_file_content
content = auto_decode(f.read())
File "/path/to/env/lib/python2.7/site-packages/pip/utils/encoding.py", line 31, in auto_decode
return data.decode(locale.getpreferredencoding(False))
LookupError: unknown encoding:
The following test code:
#!/usr/bin/env python
import sys
import locale
print sys.stdin.encoding
print locale.getpreferredencoding()
print locale.getpreferredencoding(False)
print sys.getdefaultencoding()
print sys.getfilesystemencoding()
returns:
None
US-ASCII
ascii
utf-8
From the command-line:
$ locale
LANG="en_GB.UTF-8"
LC_COLLATE="en_GB.UTF-8"
LC_CTYPE="utf-8"
LC_MESSAGES="en_GB.UTF-8"
LC_MONETARY="en_GB.UTF-8"
LC_NUMERIC="en_GB.UTF-8"
LC_TIME="en_GB.UTF-8"
LC_ALL=

According to your test the locale.getpreferredencoding() is absent — it should look like this:
UTF-8
UTF-8
US-ASCII
ascii
utf-8
Doing locale mine looks almost like yours (other than US vs GB and LC_CTYPE). It does seem peculiar that LC_CTYPE seems different, and maybe worth looking into as to why.
$ locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=
There are a couple of things you can try to correct the issue, the first being your shebang:
#!/usr/bin/python
Try changing it to this perhaps, as #!/usr/bin/env python might not set the locale properly. If that doesn't work you can always try forcing the encoding within your script:
import locale
loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
locale.setlocale(locale.LC_ALL, loc) # restore saved locale
# OR
locale.getpreferredencoding(do_setlocale=True) or "utf-8"
# OR
if locale.getpreferredencoding() == '':
locale.setlocale(locale.LC_ALL,'UTF-8')
Ultimately you'll want to figure out why locale.getpreferredencoding() is coming up empty for the first couple tests, and why you have a mismatched LC_CTYPE set in your locale.

Related

Encoding of bash terminal (representation of Cyrillic letters)

I have been using git-bash terminal, but, as I suppose, after editing font I have got a trouble - Cyrillic characters are not represented in the terminal. Instead of them it shows this: \xd0\x9f\xd1\x80\xd0\xb8\xd0\xbd\xd1\x8f\xd1\x82\xd0\xbe!.
I got this string using API:
import requests
import os
api_key = os.getenv('yandex_praktikum_api_key')
HEADERS = {
'Authorization': f'OAuth {api_key}'
}
response = requests.get(
'https://praktikum.yandex.ru/api/user_api/homework_statuses/',
params={'from_date': 0},
headers=HEADERS
)
print(response.text)
I tried to fix this by changing font back to Lucida Console (14px), but it didn't work. I checked my terminal encoding typing echo $LC_CTYPE and got ru_RU.UTF-8. Then after typing $LANG I got empty string. So, how can I fix it?
OS: Windows 10. File encoding is UTF-8. Terminal type is x-term.
Locale shows this:
User#DESKTOP-CVQ282P MINGW64 ~/Desktop
$ locale
LANG=C.UTF-8
LC_CTYPE="C.UTF-8"
LC_NUMERIC="C.UTF-8"
LC_TIME="C.UTF-8"
LC_COLLATE="C.UTF-8"
LC_MONETARY="C.UTF-8"
LC_MESSAGES="C.UTF-8"
LC_ALL=

How can I save an animation from matplotlib as a mp4 video file? [duplicate]

enter code here
# -*- coding: utf-8 -*-
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig1=plt.figure()
ax=plt.axes(xlim=(-10,10), ylim=(-10,10))
line,=ax.plot([],[],lw=1)
"""def init ():
line.set_data([],[])
return line,"""
dt=0.001
X=[]
Y=[]
r=float(input("Enter the radius :: "))
w=float(input("Enter angular frequency :: "))
def run(data):
t=0
while w*t<=2*math.pi:
x=r*math.cos(w*t)
y=r*math.sin(w*t)
X.append(x)
Y.append(y)
t=t+dt
line.set_data(X,Y)
return line,
line,=ax.plot(X,Y,lw=2)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
anim=animation.FuncAnimation(fig1,run,frames=200,interval=20,blit=True)
anim.save('amim.mp4',writer=writer)
The error message shown is ::
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/home/tathagata/Documents/Python scripts/circleamim.py", line 35, in <module>
FFMpegWriter = animation.writers['ffmpeg']
File "/home/tathagata/anaconda3/lib/python3.4/site-packages/matplotlib/animation.py", line 81, in __getitem__
return self.avail[name]
KeyError: 'ffmpeg'
I use anacoda distribution and SPYDER as my IDE. I have seen the many solutions related to key errors. But the movie wont run. How can I make the movie to run? I hope there are no other logical errors.
First install ffmpeg and add path to ffmpeg
# on windows
plt.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe'
# on linux
plt.rcParams['animation.ffmpeg_path'] = u'/home/username/anaconda/envs/env_name/bin/ffmpeg'
Note for linux users: The path for ffmpeg can be found by simply using which: which ffmpeg
Also instead of
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
I just used writer = animation.FFMpegWriter()
It seems that ffmpegis not installed on your system. Try the following code:
import matplotlib.animation as animation
print(animation.writers.list())
It will print out a list of all available MovieWriters. If ffmpegis not among it, you need to install it first from the ffmpeg homepage.
If you have Homebrew, literally just run the command
brew install ffmpeg
And Homebrew will take care of the rest (dependencies, etc). If you don't, I would recommend getting Homebrew or something like it (apt-get on Linux is built in, or an alternative on OS X would be Macports)
I have also posed with same problem(keyError: 'ffmpeg') but instead of using anakonda, I used IDLE3. So, first i checked for 'ffmpeg' in terminal it wasn't installed so installed it.
Using: sudo apt install ffmpeg
and when I run my save_animation program, it worked generating animation files in '.mpeg' format.

ActionView::Template::Error (incompatible character encodings: ASCII-8BIT and UTF-8) with portuguese brazilian characters

I'm trying to deploy an application on an Ubuntu 14.02 server with NGINX and PUMA and when I try to access static pages on the server with characters in brazilian portuguese and WITHOUT access to the database, the page is not showed and the following error gets logged:
ActionView::Template::Error (incompatible character encodings: ASCII-8BIT and UTF-8)
I read a lot of posts/answers regarding this error and tried everything.
Ruby version: ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-linux]
Rails version: Rails 4.2.4
The command locale in the server return the following:
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8
My application.rb contains the line:
config.encoding = "utf-8"
My environment.rb contais the lines:
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
I already putted the # encoding: "utf-8" on top of my html.erb files without success.
Check that the offending source files actually use the UTF-8 encoding (for example, Textmate allows to save the file using various encodings). Check whether the file is actually recognized by the system as UTF, running file /path/to/something should return UTF-8.
Also if you have just a few of those badly encoded strings you can try something like this:
the_bad_string.dup.force_encoding("UTF-8")
This should convert whatever it was to UTF.

what is the encoding of the subprocess module output in Python 2.7?

I'm trying to retrieve the content of a zipped archive with python2.7 on 64bit windows vista. I tried by making a system call to 7zip (my favourite archive manager) using the subprocess module:
# -*- coding: utf-8 -*-
import sys, os, subprocess
Extractor = r'C:\Program Files\7-Zip\7z.exe'
ArchiveName = r'C:\temp\bla.zip'
output = subprocess.Popen([Extractor,'l','-slt',ArchiveName],stdout=subprocess.PIPE).stdout.read()
This works fine as long as the archive content contains only ascii filenames, but when I try it with non-ascii I get an encoded output string variable where ä, ë, ö, ü have been replaced by \x84, \x89, \x94, \x81 (etcetera). I've tried all kinds of decode/encode calls but I'm just too inexperienced with python (and generally too stupid) to reproduce the original characters with umlaut (which is required if I would like to follow-up this step with e.g. an extraction subprocess call to 7z).
Simply put my question is: How do I get this to work also for archives with non-ascii content?
... or to put it in a more convoluted way: Is the output of subprocess always of a fixed encoding or not?
In the former case -> Which encoding is it?
In the latter case -> How can I control or uncover the encoding of the output of subprocess? Inspired by similar questions on this blog I've tried adding
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
and I've also tried
my_env = os.environ
my_env['PYTHONIOENCODING'] = 'utf-8'
output = subprocess.Popen([Extractor,'l','-slt',ArchiveName],stdout=subprocess.PIPE,env=my_env).stdout.read()
but neither seems to alter the encoding of the output variable (or to reproduce the umlaut).
You can try using the -sccUTF-8 switch from 7zip to force the output in utf-8.
Here is ref page: http://en.helpdoc-online.com/7-zip_9.20/source/cmdline/switches/scc.htm

Using windows command line to run python script with passing of url argument

I am writing this Python program which extracts some information from a webpage and I am required to run it using the windows command line. But I could not even print the original html page as a string. I am using Python 2.7
Here is my Python script:
#sys.py
import sys
import urllib
url = sys.argv[1]
f = urllib.urlopen(url)
print f.read()
When I try to run it from windows command line with: C...>sys.py "www.marinetraffic.com/ais/shipdetails.aspx?mmsi=311389000"
Errors appear as follows:
Traceback(most recent call last):
File "C:\...\sys.py", line 14 in <module>
f = urllib.urlopen(url)
File "C:\Python27\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "C:\Python27\lib\urllib.py", line 208, in open
return getattr(self, name)(url)
File "C:\Python27\lib\urllib.py", line 463, in open_file
return self.open_local_file(url)
File "C:\Python27\lib\urllib.py", line 87, in open_loca_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] The system cannot find the path specified: 'www.marinetraffic.com\\ais\\shipdetails.aspx?mmsi=311389000'
There should not be any problem with the Python set up under the windows environment because I can still print out the sys.argv list as the arguments are passed in the command line.
Is it the problem with the 'urllib' library?
Is there any another way to run this using windows command line?
I think the problem is the way you specify your url, it needs to have the http:// part at the start.
It works for me when I type
python sys.py http://www.google.com/
but fails with
python sys.py www.google.com
(Note that I am using linux with python 2.7 but I think it may be the same problem for you)

Resources