Category Archives: Python

[Solved] Windows installation uwsgi error: AttributeError: module’os’ has no attribute’uname’

Win10 system does not support the installation of UWSGI, no need to try

installation

pip install uwsgi

windows installation error

AttributeError: module’os’ has no attribute’uname’

Error description:

It is because in the uwsgiconfig.py file, os.uname() does not support windows systems, and the platform module supports any system.

solution:

uwsgi offline installation:

https://pypi.python.org/pypi/uWSGI/

Put it into the virtual environment of the project, as shown in the figure below:

Modify the os.uname() in the uwsgiconfig.py file to platform.uname().

before fixing:

import os
 import re
 import time
​
uwsgi_os = os.uname()[0]
uwsgi_os_k = re.split( ' [-+_] ' , os.uname()[2 ])[0]
uwsgi_os_v = os.uname()[3 ]
uwsgi_cpu = os.uname()[4]

After modification

import os
 import re
 import time
 import platform
​
uwsgi_os = platform.uname()[0]
uwsgi_os_k = re.split( ' [-+_] ' , platform.uname()[2 ])[0]
uwsgi_os_v = platform.uname()[3 ]
uwsgi_cpu = platform.uname()[4]

Enter the catalog

cd E:\WorkSpace\Python_worksapce\AXF\venv\Lib\site-packages\uWSGI-2.0.19.1

carried out:

python setup.py install

Error description: C language compilation environment needs to be installed

If there is no C compilation environment on this machine, you need to download a compiler

Solution to the problem of “TypeError: Assignment to constant variable”

In the process of project development, if you are not careful when using variable declarations, you may cause type errors
such as:

Uncaught (in promise) TypeError: Assignment to constant variable. Uncaught (in promise) TypeError: Assignment to constant variable
.

Reason:
We use const to define the variable and there is an initial value. Assign a value to this variable later, so an error was reported.

The ES6 standard introduces a new keyword const to define constants. Both const and let have block-level scope:

The value of a constant defined by const cannot be modified, and the defined constant must be assigned an initial value;
let defines a variable, which can be assigned to a variable without initial value assignment.
This error is caused because we modified the constant. Although some browsers do not report an error, it has no effect!

Solution:
Change const to let to declare.

Python pandas merge cannot merge two data frames based on column names (Key Error)?

toss

I am used to R for data analysis, and I feel that pandas is a bit anti-human to use. When processing data with pandas in python today, the two data frames simply cannot be merged.

I have two data frames, the column names are unknown, I can only know the index, and which two indexes are used as the primary key merge. (Don’t ask me why the listing is unknown, because I am a development tool).

The idea is to find the primary key column, rename it, and merge it.

df1.columns.values[args.marker1-1]="markerID"
df2.columns.values[args.marker2-1]="markerID"
pd.merge(df1,df2,on='markerID')

But the result is that it cannot be merged anyway. Report an error KeyError:'markerID'.

I checked it online and said that columns.valuesassignments cannot be used directly , and they must be separated. then:

colnames_df1 = df1.columns
colnames_df1[args.marker1-1] = "markerID"
df1.columns = colnames_df1
colnames_df2 = df2.columns
colnames_df2[args.marker1-1] = "markerID"
df2.columns = colnames_df2
pd.merge(df1,df2,on='markerID')

There is actually no difference.TypeError: Index does not support mutable operations

Print out all the column names of the data frame. It seems normal. Why can’t it be merged?

Use a very rough method:

pd.merge(df1,df2,left_index=True,right_index=True)

For most of the data, but some data is not, and no error is reported, the result is wrong, there is a great risk.

Solution

Finally, I checked on the Internet and finally found the answer.

Reason:
The primary key names of the two data frames look the same, but may actually be different because they may contain spaces. how come? No solution.

The solution is to remove any spaces that may exist in the column names.

method one:

df1.columns = df1.columns.str.strip() 
df2.columns=df2.columns.str.strip()

Method 2:
Remove when the data is read in.

pd.read_csv(file,sep='\s*,\s*') 
# delimiter includes x*whitespace before and after

The data corresponding to me is:

df1.columns = df1.columns.str.strip()
df2.columns = df2.columns.str.strip()
mrkid = df1.columns.values[args.marker-1]
df1.columns.values[args.marker-1]="markerID"
mergesnp = pd.merge(df1,df2,on='markerID')
mergesnp.columns.values[args.marker-1]=mrkid

Python Error: Socket TypeError: a bytes-like object is required, not ‘str’ [How to Solve]

In the third edition of Python core programming, we found that the return error of example 2-1 code… Tangled for a long time
we found that there is a difference in socket return value decoding between Python 3.5 and python 2.7
let’s first introduce the function encode(), decode() of Python bytes and STR type conversion

STR can be encoded to the specified bytes by encode() method

Conversely, if we read a byte stream from the network or disk, the data we read is bytes. To change bytes into STR, you need to use the decode () method:

2-1 examples in Python core programming book

TCP server:

#coding=utf-8
#Creating a TCP server
from socket import *
from time import ctime HOST='' PORT=21567 BUFSIZ=1024 ADDR=(HOST,PORT) tcpSerSock=socket(AF_INET,SOCK_STREAM) #create server sockets tcpSerSock. bind(ADDR) #Bind the socket to the address tcpSerSock.listen(5) #Listen for connections, pass in the maximum number of connection requests while True: print('waiting for connection...') tcpCliSock,addr =tcpSerSock.accept() print('...connected from:',addr) while True: data =tcpCliSock.recv(BUFSIZ) #print('date=',data) if not data: break tcpCliSock.send(('[%s] %s' %(ctime(),data))) tcpCliSock.close() tcpSerSock.close()

TCP client

#coding=utf-8

from socket import *

HOST = 'localhost' # or 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR=(HOST,PORT) tcpCliSock = socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = input('> ') print('data=',data); if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break print(data) tcpCliSock.close() 

Returned error message.
TypeError: a bytes-like object is required, not ‘str’
This refers to line 18 tcpCliSock.send(data) where the argument passed in is supposed to be of type bytes, not str.

 

How to Solve:

In python 3, bytes strings and unicodestrings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly differentinterface from unicode strings.

So, now, whenever you have a unicode stringthat you need to use as a byte string, you need toencode() it. And whenyou have a byte string, you need to decode it to use it as a regular(python 2.x) string.

Unicode strings are quotes enclosedstrings. Bytes strings are b”” enclosed strings

When you use client_socket.send(data),replace it by client_socket.send(data.encode()). When you get datausing data = client_socket.recv(512), replace it by data =client_socket.recv(512).decode()

So I went to check the help manual for python 3.5.

socket.send(bytes[, flags])

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.recv(bufsize[, flags])

Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

Note

For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

After correction:

TCP server

#coding=utf-8
#Creating a TCP server
from socket import *
from time import ctime HOST='' PORT=21567 BUFSIZ=1024 ADDR=(HOST,PORT) tcpSerSock=socket(AF_INET,SOCK_STREAM) #创服务器套接字 tcpSerSock.bind(ADDR) #套接字与地址绑定 tcpSerSock.listen(5) #监听连接,传入连接请求的最大数 while True: print('waiting for connection...') tcpCliSock,addr =tcpSerSock.accept() print('...connected from:',addr) while True: data =tcpCliSock.recv(BUFSIZ).decode() print('date=',data) if not data: break tcpCliSock.send(('[%s] %s' %(ctime(),data)).encode()) tcpCliSock.close() tcpSerSock.close()

TCP client:

#coding=utf-8

from socket import *

HOST = 'localhost' # or 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR=(HOST,PORT) tcpCliSock = socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = input('> ') #print('data=',data); if not data: break tcpCliSock.send(data.encode()) data = tcpCliSock.recv(BUFSIZ).decode() if not data: break print(data) tcpCliSock.close()

socket.sendto(bytes, address)
socket.sendto(bytes, flags, address)

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.recvfrom(bufsize[, flags])

  Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

Similarly, modify the UDP server

from socket import *
from time import ctime
HOST='' PORT=21546 BUFSIZ=1024 ADDR=(HOST,PORT) udpSerSock = socket(AF_INET,SOCK_DGRAM) udpSerSock.bind(ADDR) while True: print('waiting for message...') data,addr=udpSerSock.recvfrom(BUFSIZ) data=data.decode() udpSerSock.sendto(('[%s] %s'%(ctime(),data)).encode(),addr) print('...received from and returned to:',addr) udpSerSock.close()

[Solved] Python Error: a bytes-like object is required, not ‘str’

Core code:

def ipPools(numPage):
    headers = randomHeads()
    url = 'http://www.xicidaili.com/nn/'
    saveFsvFile = open('ips.csv', 'wb')
    writer = csv.writer(saveFsvFile)
    for num in range(1, numPage + 1):
        full_url = url + str(num)
        re = requests.get(full_url, headers=headers)
        soup = BeautifulSoup(re.text, 'lxml')
        res = soup.find(id="ip_list").find_all('tr')
        for item in res:
            try:
                temp = []
                tds = item.find_all('td')
                proxyIp = tds[1].text.encode("utf-8")
                proxyPort = tds[2].text.encode("utf-8")
                temp.append(proxyIp)
                temp.append(proxyPort)
                writer.writerow(temp)
                print('保存为excel成功!')
            except IndexError:
                pass
Points to note.
   Be sure to convert str to bytes :
   str.encode("utf-8")
   python36 file method to open
   open('ips.csv', 'wb') change wb to w I got an error right here.  If there is the same error can, as a reference it!

Python sublime3 [Decode error – output not utf-8] Chinese display problem

Generally speaking, this is a coding problem

The problem can be solved by sacrificing big killers

# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
print '你好'
>>>你好

But today we are talking about another problem

Running in sublime is [decode error – output not UTF-8]

There is no problem running under CMD

The code is as follows

# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

print "GOOD-成功"

cmdDown

Delete

#The coding is fine, it's a bug in sublime
#Change it to print "GOOD-success-GOOD" and it will be fine
#The solution is to put a space at the end

print "GOOD-Success"
#Tested several positions and they all work
print "success-GOOD"
print "success-GOOD-success"
#Summarize that you can't start with Chinese and end with Chinese

Python OpenCV BUG: all the input arrays must have same number of dimensions

Abnormal interpretation

When using OpenCV to write code, there will be a valueerror: all the input arrays must have the same number of dimensions error

The error is a value error. For example, the following code will report an error

import cv2 as cv
import numpy as np

# Read the grayscale image
image1 = cv.imread("11.jpg", 0)
# Read the color image
image2 = cv.imread("11.jpg")

# Error location
image = np.hstack((image1, image2))

cv.imshow("img", image)
cv.waitKey()

The reason for this bug is that [image dimensions are different], and the influence functions are NP. Hstack ((M1, M2)) , NP. Column_ stack((m1,m2))np.concatenate([m1, m2])

Exception resolution

Modify the image dimension, check the different positions of the image dimension, and adjust it

The specific code is different, we can adjust it by ourselves

Appendix

This series of articles is only for recording the bugs encountered in the process of Python daily development and providing them to students as reference data and solutions. It belongs to the recording blog, and readers who are destined to see it hope to solve your problems

Error prompt template can be compared with your error

Traceback (most recent call last):
  File "e:/crawl100/opencv_ppt/error.py", line 10, in <module>
    image = np.hstack((image1, image2)).toarray()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\core\shape_base.py", line 340, in hstack
    return _nx.concatenate(arrs, 1)
ValueError: all the input arrays must have same number of dimensions

[Solved] Python Error: /usr/bin/python^M: bad interpreter: No such file or directory

The main reason is ^ M

This is caused by different system coding formats: the. Sh. Py file edited in Windows system may have invisible characters, so the above abnormal information will be reported when executing in Linux system. It is usually caused by the different identification of the end of windows line and Linux line

Solution:

1) Conversion in Windows:

Use some editors, such as UltraEdit or EDITPLUS, to encode and convert scripts first, and then put them into Linux for execution. The conversion method is as follows (UltraEdit): File — > Conversions–> DOS-> UNIX is fine

2) Direct replacement under Linux

Sed – I’s/^ m// g ‘file name

3) It can also be converted in Linux

First, make sure that the file has executable permissions

#sh> chmod a+x filename

Then change the file format

#sh> vi filename

Use the following command to view the file format

: set FF or: set fileformat

You can see the following information

Fileformat = DOS or fileformat = UNIX

Use the following command to modify the file format

: set FF = UNIX or: set fileformat = UNIX

: WQ (save and exit)

Finally, execute the file

#sh>./ filename

[Solved] Python redis Sorted Set Error: ‘str’ object has no attribute ‘items’

redis.zadd('language', 'C', 1)

Add an element to the sorted set and report an error ‘STR’ object has no attribute ‘items’

Error source

        for pair in iteritems(mapping):
            pieces.append(pair[1])
            pieces.append(pair[0])

We need a dictionary here

Modification

redis.zadd('language', {'C': 1})

Done!