g.next() has been renamed to g.__next__(). The reason for this is consistency: special methods like __init__() and __del__() all have double underscores (or “dunder” in the current vernacular), and .next() was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]
Traceback(most recent call last):File"C:/Python26/test18.py", line 31,in<module>
storvars(mydict)File"C:/Python26/test18.py", line 14,in storvars
pickle.dump(vdict,f,)TypeError: must be str,not bytes
I’m using python3.3 and I’m having a cryptic error when trying to pickle a simple dictionary.
Here is the code:
import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')
def storvars(vdict):
f = open('varstor.txt','w')
pickle.dump(vdict,f,)
f.close()
return
mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)
and I get:
Traceback (most recent call last):
File "C:/Python26/test18.py", line 31, in <module>
storvars(mydict)
File "C:/Python26/test18.py", line 14, in storvars
pickle.dump(vdict,f,)
TypeError: must be str, not bytes
Just had same issue. In Python 3, Binary modes ‘wb’, ‘rb’ must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that’s why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
I know about a single and double asterisks preceding arguments (for variable number of arguments), but this precedes nothing. And I’m pretty sure this has nothing to do with pickle. That’s probably just an example of this happening. I only learned its name when I sent this to the interpreter:
>>> def func(*):
... pass
...
File "<stdin>", line 1
SyntaxError: named arguments must follow bare *
Bare * is used to force the caller to use named arguments – so you cannot define a function with * as an argument when you have no following keyword arguments.
The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to
allow for keyword-only arguments for functions that would not
otherwise take a varargs argument:
def compare(a, b, *, key=None):
...
While the original answer answers the question completely, just adding a bit of related information. The behaviour for the single asterisk derives from PEP-3102. Quoting the related section:
The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to
allow for keyword-only arguments for functions that would not
otherwise take a varargs argument:
def compare(a, b, *, key=None):
...
In simple english, it means that to pass the value for key, you will need to explicitly pass it as key="value".
回答 2
def func(*, a, b):print(a)print(b)
func("gg")# TypeError: func() takes 0 positional arguments but 1 was given
func(a="gg")# TypeError: func() missing 1 required keyword-only argument: 'b'
func(a="aa", b="bb", c="cc")# TypeError: func() got an unexpected keyword argument 'c'
func(a="aa", b="bb","cc")# SyntaxError: positional argument follows keyword argument
func(a="aa", b="bb")# aa, bb
上面带有** kwargs的示例
def func(*, a, b,**kwargs):print(a)print(b)print(kwargs)
func(a="aa",b="bb", c="cc")# aa, bb, {'c': 'cc'}
>>>def f(a,*, b):...return a + b
...>>> f(1,2)Traceback(most recent call last):File"<stdin>", line 1,in<module>TypeError: f() takes 1 positional argument but 2 were given
>>> f(1, b=2)3
Semantically, it means the arguments following it are keyword-only, so you will get an error if you try to provide an argument without specifying its name. For example:
>>> def f(a, *, b):
... return a + b
...
>>> f(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1, b=2)
3
Pragmatically, it means you have to call the function with a keyword argument. It’s usually done when it would be hard to understand the purpose of the argument without the hint given by the argument’s name.
Compare e.g. sorted(nums, reverse=True) vs. if you wrote sorted(nums, True). The latter would be much less readable, so the Python developers chose to make you to write it the former way.
def test_args_kwargs(arg1, arg2, arg3):print"arg1:", arg1
print"arg2:", arg2
print"arg3:", arg3
# first with *args>>> args =("two",3,5)>>> test_args_kwargs(*args)
arg1: two
arg2:3
arg3:5# now with **kwargs:>>> kwargs ={"arg3":3,"arg2":"two","arg1":5}>>> test_args_kwargs(**kwargs)
arg1:5
arg2: two
arg3:3
With the demonstration function defined first below, there are two examples, one with *args and one with **kwargs
def test_args_kwargs(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
# first with *args
>>> args = ("two", 3,5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5
# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3
So *args allows you to dynamically build a list of arguments that will be taken in the order in which they are fed, whereas **kwargs can enable the passing of NAMED arguments, and can be processed by NAME accordingly (irrespective of the order in which they are fed).
The site continues, noting that the correct ordering of arguments should be:
Your path only lists Visual Studio 11 and 12, it wants 14, which is Visual Studio 2015. If you install that, and remember to tick the box for Languages->C++ then it should work.
On my Python 3.5 install, the error message was a little more useful, and included the URL to get it from
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
I can’t believe no one has suggested this already – use the binary-only option for pip. For example, for mysqlclient:
pip install --only-binary :all: mysqlclient
Many packages don’t create a build for every single release which forces your pip to build from source. If you’re happy to use the latest pre-compiled binary version, use --only-binary :all: to allow pip to use an older binary version.
请注意,如果您已经安装了Visual Studio,则在运行安装程序时可以修改您的安装程序(在Visual Studio Community 2017下单击“修改”按钮)并执行步骤3和4
最后的注意事项:如果您不想安装所有模块,那么拥有下面的3个模块(或VC ++ 2017的较新版本)就足够了。(您也可以仅使用这些选项来安装Visual Studio Build Tools,因此您不需要安装Visual Studio Community Edition本身)=>此最小安装已经是4.5GB,因此保存所有内容都会有所帮助
Select free download under Visual Studio Community 2017. This will download the installer. Run the installer.
Select what you need under workload tab:
a. Under Windows, there are 3 choices. Only check Desktop development with C++
b. Under Web & Cloud, there are 7 choices. Only check Python development (I believe this is optional But I have done it).
In cmd, type pip3 install misaka
Note if you already installed Visual Studio then when you run the installer, you can modify yours (click modify button under Visual Studio Community 2017) and do steps 3 and 4
Final Note : If you don’t want to install all modules, having the 3 ones below (or a newer version of the VC++ 2017) would be sufficient. (you can also install the Visual Studio Build Tools with only these options so you dont need to install Visual Studio Community Edition itself) => This minimal install is already a 4.5GB, so saving off anything is helpful
As the other responses pointed out, one solution is to install Visual Studio 2015. However, it takes a few GBs of disk space. One way around is to install precompiled binaries. The webpage http://www.lfd.uci.edu/~gohlke/pythonlibs (mirror) contains precompiled binaries for many Python packages. After downloading the package of interest to you, you can install it using pip install, e.g. pip install mysqlclient‑1.3.10‑cp35‑cp35m‑win_amd64.whl.
I’d recommend saving that wheel file in the directory where you’ve installed Python i.e somewhere in Local Disk C
Then visit the folder where the wheel file exists and run pip install <*wheel file's name*>
Finally run the command pip install Scrapy again and you’re good to use Scrapy or any other tool which required you to download massive Windows C++ Package/SDK.
Disclaimer: This solution worked for me while trying to install Scrapy, but I can’t guarantee the same happening while installing other softwares/packages/etc.✌
回答 5
我在尝试安装时遇到了这个确切的问题mayavi。
因此,error: Microsoft Visual C++ 14.0 is required在安装库时,我也有共同点。
转到Visual Studio 2017的构建工具并安装Build Tools for Visual Studio 2017。下All downloads(向下滚动)>>Tools for Visual Studio 2017
如果已经安装,请跳至2。
选择C++ Components您需要的(我不知道我需要哪个,所以安装了许多)。
如果已经安装,Build Tools for Visual Studio 2017则打开应用程序,Visual Studio Installer然后转到Visual Studio Build Tools 2017>> Modify>>,Individual Components然后选择所需的组件。
从其他的答案中的重要组成部分似乎是:C++/CLI support,VC++ 2017 version <...> latest,Visual C++ 2017 Redistributable Update,Visual C++ tools for CMake,Windows 10 SDK <...> for Desktop C++,Visual C++ Build Tools core features,Visual Studio C++ core features。
为安装/修改这些组件Visual Studio Build Tools 2017。
这是重要的一步。打开应用程序,Visual Studio Installer然后转到Visual Studio Build Tools>> Launch。这将在正确的位置打开CMD窗口Microsoft Visual Studio\YYYY\BuildTools。
I had this exact issue while trying to install mayavi.
So I also had the common error: Microsoft Visual C++ 14.0 is required when pip installing a library.
After looking across many web pages and the solutions to this thread, with none of them working. I figured these steps (most taken from previous solutions) allowed this to work.
Go to Build Tools for Visual Studio 2017 and install Build Tools for Visual Studio 2017. Which is under All downloads (scroll down) >> Tools for Visual Studio 2017
If you have already installed this skip to 2.
Select the C++ Components you require (I didn’t know which I required so installed many of them).
If you have already installed Build Tools for Visual Studio 2017 then open the application Visual Studio Installer then go to Visual Studio Build Tools 2017 >> Modify >> Individual Components and selected the required components.
From other answers important components appear to be: C++/CLI support, VC++ 2017 version <...> latest, Visual C++ 2017 Redistributable Update, Visual C++ tools for CMake, Windows 10 SDK <...> for Desktop C++, Visual C++ Build Tools core features, Visual Studio C++ core features.
Install/Modify these components for Visual Studio Build Tools 2017.
This is the important step. Open the application Visual Studio Installer then go to Visual Studio Build Tools >> Launch. Which will open a CMD window at the correct location for Microsoft Visual Studio\YYYY\BuildTools.
Now enter python -m pip install --upgrade setuptools within this CMD window.
Finally, in this same CMD window pip install your python library: pip install -U <library>.
回答 6
安装spaCy模块时遇到相同的问题。我检查了控制面板,我已经安装了几个可视的C ++可再发行组件。
我所做的是选择已经安装在我的PC上的“ Microsoft Visual Studio Community 2015”->“修改”->选中“ Visual C ++ 2015通用工具”。然后,将花费一些时间并下载超过1 GB的空间进行安装。
I had the same problem when installing spaCy module. And I checked control panel I have several visual C++ redistributables installed already.
What I did was select “Microsoft Visual Studio Community 2015” which is already installed on my PC –> “Modify” –>check “Common Tools for Visual C++ 2015”. Then it will take some time and download more than 1 GB to install it.
After reading a lot of answers in SO and none of them working, I finally managed to solve it following the steps in this thread, I will leave here the steps in case the page dissapears:
Please try to install Build Tools for Visual Studio 2017, select the workload “Visual C++ build tools” and check the options “C++/CLI support” and “VC++ 2015.3 v14.00 (v140) toolset for desktop” as below.
You should now no longer use Visual Studio Tools 2015 since a newer version is available. As indicated by the Python documentation you should be using Visual Studio Tools 2017 instead.
Visual C++ Build Tools 2015 was upgraded by Microsoft to Build Tools for Visual Studio 2017.
Use this link to download and install Visual C++ 2015 Build Tools. It will automatically download visualcppbuildtools_full.exe and install Visual C++ 14.0 without actually installing Visual Studio. After the installation completes, retry pip install and you won’t get the error again.
I have tested it on following platform and versions:
Python 3.6 on Windows 7 64-bit
Python 3.8 on Windows 10 64-bit
I have same suggestion as a comment to the question, however, I have been requested to post this as an answer as it helped a lot of people. So I posted it as an answer.
I am on python3.7 & windows 10 and installing Microsoft Build Tools for Visual Studio 2017 (as described here) did not solve my problem that was identical to yours.
I had the same problem. I needed a 64-bit version of Python so I installed 3.5.0 (the most recent as of writing this). After switching to 3.4.3 all of my module installations worked.
None of the solutions here and elsewhere worked for me. Turns out an incompatible 32bit version of mysqlclient is being installed on my 64bit Windows 10 OS because I’m using a 32bit version of Python
I had to uninstall my current Python 3.7 32bit, and reinstalled Python 3.7 64bit and everything is working fine now
Just go to https://www.lfd.uci.edu/~gohlke/pythonlibs/ find your suitable package (whl file). Download it. Go to the download folder in cmd or typing ‘cmd’ on the address bar of the folder. Run the command :
pip install mysqlclient-1.4.6-cp38-cp38-win32.whl
(Type the file name correctly. I have given an example only). Your problem will be solved without installing build toll cpp of 6GB size.
回答 21
在@Sushant Chaudhary的答案之上添加
就我而言,我又遇到了有关lxml的另一个错误,如下所示
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-3.7\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
error:MicrosoftVisual C++14.0is required.Get it with"Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
in my case, I got another error regarding lxml as below
copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-3.7\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
I had to install lxml‑4.2.3‑cp37‑cp37m‑win_amd64.whl same way as in the answer of @Sushant Chaudhary to successfully complete installation of Scrapy.
cd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build"
vcvarsall.bat x86_amd64
cd \
set CL=-FI"%VCINSTALLDIR%\tools\msvc\14.16.27023\include\stdint.h"
pip install pycrypto
for Python 3.7.4 following set of commands worked:
Before those command, you need to confirm Desktop with C++ and Python is installed in Visual Studio.
cd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build"
vcvarsall.bat x86_amd64
cd \
set CL=-FI"%VCINSTALLDIR%\tools\msvc\14.16.27023\include\stdint.h"
pip install pycrypto
I had the same issue while installing mysqlclient for the Django project.
In my case, it’s the system architecture mismatch causing the issue. I have Windows 7 64bit version on my system. But, I had installed Python 3.7.2 32 bit version by mistake.
So, I re-installed Python interpreter (64bit) and ran the command
pip install mysqlclient
I hope this would work with other Python packages as well.
回答 25
我在Windows 10 python版本3.8上遇到了完全相同的问题。就我而言,我需要在发生错误时安装mysqlclientMicrosoft Visual C++ 14.0 is required。因为安装Visual Studio及其软件包可能是一个乏味的过程,所以我做了以下工作:
I had the same exact issue on my windows 10 python version 3.8.
In my case, I needed to install mysqlclient were the error occurred Microsoft Visual C++ 14.0 is required. Because installing visual studio and it’s packages could be a tedious process, Here’s what I did:
step 1 – Go to unofficial python binaries from any browser and open its website.
step 2 – press ctrl+F and type whatever you want. In my case it was mysqlclient.
step 3 – Go into it and choose according to your python version and windows system. In my case it was mysqlclient‑1.4.6‑cp38‑cp38‑win32.whl and download it.
step 4 – open command prompt and specify the path where you downloaded your file. In my case it was C:\Users\user\Downloads
step 5 – type pip install .\mysqlclient‑1.4.6‑cp38‑cp38‑win32.whl and press enter.
Thus it was installed successfully, after which I went my project terminal re-entered the required command. This solved my problem
Note that, while working on the project in pycharm, I also tried installing mysql-client from the project interpreter. But mysql-client and mysqlclient are different things. I have no idea why and it did not work.
I was facing the same problem. The following worked for me:
Download the unoffical binaries file from Christoph Gohlke installers site as per the python version installed on your system.
Navigate to the folder where you have installed the file and run
pip install filename
For me python_ldap‑3.0.0‑cp35‑cp35m‑win_amd64.whl worked as my machine is 64 bit and python version is 3.5.
This successfully installed python-ldap on my windows machine. You can try the same for mysql-python
If Visual Studio is NOT your thing, and instead you are using VS Code, then this link will guide you thru the installer to get C++ running on your Windows.
What’s the correct way to convert bytes to a hex string in Python 3?
I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!
Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:
b'foo'.encode('hex')
In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):
import codecs
codecs.getencoder('hex')(b'foo')[0]
Starting with Python 3.4, there is a less awkward option:
codecs.encode(b'foo', 'hex')
These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.
import binascii
with open("addressbook.bin","rb")as f:# or any binary file like '/bin/ls'
in_bytes = f.read()print(in_bytes)# b'\n\x16\n\x04'
hex_bytes = binascii.hexlify(in_bytes)print(hex_bytes)# b'0a160a04' which is twice as long as in_bytes
hex_str = hex_bytes.decode("ascii")print(hex_str)# 0a160a04
The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.
I included an snippet that illustrates it.
import binascii
with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
in_bytes = f.read()
print(in_bytes) # b'\n\x16\n\x04'
hex_bytes = binascii.hexlify(in_bytes)
print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
hex_str = hex_bytes.decode("ascii")
print(hex_str) # 0a160a04
from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'
OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don’t specify the Python version, so here’s a way that works on both Python 2 and Python 3.
I’m also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.
Given that, the best approach I know is:
import six
bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))
The following assertion will be true for either Python 2 or Python 3, assuming you haven’t activated the unicode_literals future in Python 2:
assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'
(Or you can use ''.join() to omit the space between the bytes, etc.)
回答 6
可以使用格式说明符%x02来格式化并输出一个十六进制值。例如:
>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6">>> res ="">>>for b in foo:... res +="%02x"% b
...>>>print(res)7443fc7d05698d8605a5b4d35d56649c5a927e2736
it can been used the format specifier %x02 that format and output a hex value. For example:
>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
... res += "%02x" % b
...
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736
回答 7
python 3.8中的新增功能,您可以将定界符参数传递给hex函数,如本例所示
>>> value = b'\xf0\xf1\xf2'>>> value.hex('-')'f0-f1-f2'>>> value.hex('_',2)'f0_f1f2'>>> b'UUDDLRLRAB'.hex(' ',-4)'55554444 4c524c52 4142'
[python3.5]>>>from struct import*>>>temp=unpack('B',b'\x61')[0]## convert bytes to unsigned int97>>>hex(temp)##convert int to string which is hexadecimal expression'0x61'
If you want to convert b’\x61′ to 97 or ‘0x61’, you can try this:
[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'
From python 3.6 on you can also use Literal String Interpolation, “f-strings”. In your particular case the solution would be:
if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
...do something
EDIT:
Since there have been some questions in the comment on how to deal with special characters I’d like to extend my answer:
raw strings (‘r’):
One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:
In short:
Let’s say instead of finding a word boundary \b after TEXTO you want to match the string \boundary. The you have to write:
This only works because we are using a raw-string (the regex is preceded by ‘r’), otherwise we must write “\\\\boundary” in the regex (four backslashes). Additionally, without ‘\r’, \b’ would not converted to a word boundary anymore but to a backspace!
re.escape:
Basically puts a backspace in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:
if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
print("match")
NOTE: For any version >= python 3.7: !, ", %, ', ,, /, :, ;, <, =, >, @, and ` are not escaped. Only special characters with meaning in a regex are still escaped. _ is not escaped since Python 3.3.(s. here)
Curly braces:
If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let’s say you want to match TEXTO followed by exactly 2 digits:
if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
print("match")
print(matches[1])# prints one whole matching line (in this case, the first line)print(matches[1][3])# prints the fourth character group (established with the parentheses in the regex statement) of the first line.
I needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:
print(matches[1]) # prints one whole matching line (in this case, the first line)
print(matches[1][3]) # prints the fourth character group (established with the parentheses in the regex statement) of the first line.
You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.
if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
# Successful match**strong text**
else:
# Match attempt failed
Edit: I didn’t know how default arguments worked in Python, but for the sake of this question, I will keep the examples above. In general it’s much better to do the following:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
It’s true that’s it’s not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
If you’re using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:
Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc: export LC_ALL=C
then type source .bashrc
Now you don’t need to call this command manually every time, when you connecting via ssh for example.
While you can set the locale exporting an env variable, you will have to do that every time you start a session. Setting a locale this way will solve the problem permanently:
The first thing you should know is most of the locale config file located path can be get from localedef --help :
$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
repertoire maps: /usr/share/i18n/repertoiremaps
locale path : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>
See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:
$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN /usr/share/i18n/locales/zh_HK /usr/share/i18n/locales/zh_SG /usr/share/i18n/locales/zh_TW
Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:
And now update the system default locale with desired LANG, LC_ALL …etc with this update-locale:
sudo update-locale LANG=en_LOVE.UTF-8
update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:
$ head /etc/default/locale
# File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...
But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:
$ . /etc/default/locale
How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8
For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.
回答 5
对于Dockerfile,这对我有用:
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
This change will not be immediately evident in your current cli session unless you reload the bash profile by using: source ~/.bash_profile.
This answer is pretty close to answers that I’ve posted to other non-identical, non-duplicate questions (i.e. not related to pipenv) but which happen to require the same solution.
To the moderator: With respect; my previous answer got deleted for this reason but I feel that was a bit silly because really this answer applies almost whenever the error is “problem with locale”… but there are a number of differing situations, languages, and environments which could trigger that error.
Thus it A) doesn’t make sense to mark the questions as duplicates and B) doesn’t make sense to tailor the answer either because the fix is very simple, is the same in each case and does not benefit from ornamentation.
I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
Is there any better way to do it? something like c = a[b] ?
import pandas as pd
a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]
You can then convert c back to a list if you want:
c = list(c)
回答 3
比较五个提供的答案的执行时间的基础测试,但不是非常广泛的测试:
def numpyIndexValues(a, b):
na = np.array(a)
nb = np.array(b)
out = list(na[nb])return out
def mapIndexValues(a, b):
out = map(a.__getitem__, b)return list(out)def getIndexValues(a, b):
out = operator.itemgetter(*b)(a)return out
def pythonLoopOverlap(a, b):
c =[ a[i]for i in b]return c
multipleListItemValues =lambda searchList, ind:[searchList[i]for i in ind]
Basic and not very extensive testing comparing the execution time of the five supplied answers:
def numpyIndexValues(a, b):
na = np.array(a)
nb = np.array(b)
out = list(na[nb])
return out
def mapIndexValues(a, b):
out = map(a.__getitem__, b)
return list(out)
def getIndexValues(a, b):
out = operator.itemgetter(*b)(a)
return out
def pythonLoopOverlap(a, b):
c = [ a[i] for i in b]
return c
multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]
using the following input:
a = range(0, 10000000)
b = range(500, 500000)
simple python loop was the quickest with lambda operation a close second, mapIndexValues and getIndexValues were consistently pretty similar with numpy method significantly slower after converting lists to numpy arrays.If data is already in numpy arrays the numpyIndexValues method with the numpy.array conversion removed is quickest.
numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995
%timeit _,a1,b1,_,_,c1,_ = a
10000000 loops, best of 3:154 ns per loop
%timeit itemgetter(*b)(a)1000000 loops, best of 3:753 ns per loop
%timeit [ a[i]for i in b]1000000 loops, best of 3:777 ns per loop
%timeit map(a.__getitem__, b)1000000 loops, best of 3:1.42µs per loop
Don’t forget that if the list is small and the indexes don’t change, as in your example, sometimes the best thing is to use sequence unpacking:
_,a1,a2,_,_,a3,_ = a
The performance is much better and you can also save one line of code:
%timeit _,a1,b1,_,_,c1,_ = a
10000000 loops, best of 3: 154 ns per loop
%timeit itemgetter(*b)(a)
1000000 loops, best of 3: 753 ns per loop
%timeit [ a[i] for i in b]
1000000 loops, best of 3: 777 ns per loop
%timeit map(a.__getitem__, b)
1000000 loops, best of 3: 1.42 µs per loop
I’m a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the ‘else if’ statement. The interpreter gives me a syntax error after the ‘if’ in ‘else if’ for a reason I can’t seem to figure out.
def function(a):
if a == '1':
print ('1a')
else if a == '2'
print ('2a')
else print ('3a')
function(input('input:'))
I’m probably missing something very simple; however, I haven’t been able to find the answer on my own.
def function(a):
if a == '1':
print ('1a')
else if a == '2'
print ('2a')
else print ('3a')
Should be corrected to:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
As you can see, else if should be changed to elif, there should be colons after ‘2’ and else, there should be a new line after the else statement, and close the space between print and the parentheses.