Category Archives: Python

sudo: pip:command not Find problem solving

python3

sudo apt-get install python3-pip

python2

sudo apt-get install python-pip
If it still does not work, follow the steps below

Reason: The -with-secure-path option was added when compiling sudo.

Solution: add an alias to the environment configuration file

(1) vi ~/.bashrc

Add the following content:

alias sudo=’sudo env PATH=$PATH’

(2) source ~/.bashrc

 

The solution of ‘STR’ object has no attribute ‘get’ error

I used the requests.get()method when writing a crawler in python :

DEF OpenURL (URL, IP, Agent):
     # function parameter is url: web page address; ip: ip pool; agent: User-Agent, three are string type 
    requests.get (url, headers = agent, proxies = ip)

What is puzzled is that the’str’ object has no attribute’get’ error was reported when using it

After reviewing the documentation, it was found that the headers and proxies parameters in the get() method should be passed in a dictionary instead of a string , so after modification, the code runs successfully:

def openUrl(url, ip, agent):
    headers = { ' User-Agent ' : agent}
    proxies = { ' http ' : ip}
    requests.get(url, headers =headers, proxies=proxies)

 

Python3.x Error:AttributeError: ‘str’ object has no attribute ‘decode’

Python 3. X: attributeerror: ‘STR’ object has no attribute ‘decode’

1. There are some differences between Python 3.X and python 2.X. I encountered two problems as follows:

a. First report: mysqlclient version 1.3 is wrong:

Solution: comment out the line

b. Second, the problem of character set

The error is as follows: file “C:// users/administrator/pcharmprojects/untitled1/venv/lib/site packages/Django/db/backends/MySQL/operations. Py”, line 146, in last_ executed_ query

query = query.decode(errors=’replace’)

AttributeError: ‘str’ object has no attribute ‘decode’

Solution: Comment out here because the character set is not supported

Python Send Email Error: smtplib.SMTPException: SMTP AUTH extension not supported by server

Python sends e-mail. The 126 e-mail box used before is normal, but today it is changed to Hotmail, and this error has been reported all the time

smtplib.SMTPE xception:SMTPAUTHextensionnotsupportedbyserver

my previous code is as follows:

def sendmail(receivers,mailtitle,mailcontent):

    ret=True
    # try:
    # msg=MIMEText(mailcontent,'plain','utf-8')
    msg = MIMEText(mailcontent, 'html', 'utf-8')
    msg['From']=formataddr(["I'm Black",sender]) # brackets correspond to sender's email nickname, sender's email account
    # msg['To']=formataddr(["Recipient nickname",receivers]) # The one in brackets corresponds to the recipient's email nickname, recipient's email account
    msg['Subject']=mailtitle # The subject of the message, also known as the title

    server = None
    # Determine if it is an SSL connection
    if flag_mail_ssl:
        server=smtplib.SMTP_SSL(mail_host, mail_port) # SMTP server in sender's mailbox
    else:
        server=smtplib.SMTP(mail_host, mail_port)#
    server.login(mail_user, mail_pass) # the brackets correspond to the sender's mailbox account, mailbox password
    server.sendmail(sender,receivers,msg.as_string()) # The brackets correspond to the sender's mailbox account, the recipient's mailbox account, and the sent mail
    server.quit()# close the connection
    # except Exception as e:# If the statement in try is not executed, the following ret=False will be executed
    # ret=False
    return ret

After searching the Internet, add the following two lines of code before login:

server.ehlo() # Send SMTP 'ehlo' command to Gamil
server.starttls()

That’s it. The final code is:

def sendmail(receivers,mailtitle,mailcontent):
    ret=True
    # try:
    # msg=MIMEText(mailcontent,'plain','utf-8')
    msg = MIMEText(mailcontent, 'html', 'utf-8')
    msg['From']=formataddr(["I'm Black",sender]) # brackets correspond to sender's email nickname, sender's email account
    # msg['To']=formataddr(["Recipient nickname",receivers]) # The one in brackets corresponds to the recipient's email nickname, recipient's email account
    msg['Subject']=mailtitle # The subject of the message, also known as the title

    server = None
    # Determine if it is an SSL connection
    if flag_mail_ssl:
        server=smtplib.SMTP_SSL(mail_host, mail_port) # SMTP server in sender's mailbox
    else:
        server=smtplib.SMTP(mail_host, mail_port)#
    server.ehlo() # Send SMTP 'ehlo' command to Gamil
    server.starttls()
    server.login(mail_user, mail_pass) # The corresponding mailbox account and mailbox password in parentheses is the sender's mailbox
    server.sendmail(sender,receivers,msg.as_string()) # The mail accounts in parentheses are the sender's mailbox account, the recipient's mailbox account, and the sent mail
    server.quit()# close the connection
    # except Exception as e:# If the statement in try is not executed, the following will be executed ret=False
    #     ret=False
    return ret

 

Python Installation WARNING: pip is configured with locations that require TLS/SSL, however the ssl module…

How to solve python Installation WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.

1. Install the relevant dependencies

yum install gcc libffi-devel zlib* openssl-devel
# libffi-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make

2. Download and unzip
wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tar.xz
# Download
wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tar.xz
# Unzip and compile.
tar -xvJf Python-3.7.1.tar.xz
cd Python-3.7.1

3. Compile and install
. /configure prefix=/usr/local/python3
make && make install
# After compiling, create a softlink file to the executable path.
ln -s /usr/local/python3/bin/python3 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3
# We can clear the previously compiled executables and configuration files && Clear all generated files:.
make clean && make distclean

bug: Failed to use pip command
2.1 Error messages
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting virtualenv
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)’: /simple/virtualenv/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)’: /simple/virtualenv/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)’: /simple/virtualenv/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)’: /simple/virtualenv/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)’: /simple/virtualenv/
Could not fetch URL https://pypi.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host=’pypi.org’, port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)) – skipping
Could not find a version that satisfies the requirement virtualenv (from versions: )
No matching distribution found for virtualenv
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host=’pypi.org’, port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(“Can’t connect to HTTPS URL because the SSL module is not available.”)) – skipping

2.2 Reason
System version centos6.5, where openssl version is OpenSSL 1.0.1e-fips 11 Feb 2013, and python3.7 needs openssl version 1.0.2 or 1.1.x, need to upgrade openssl and recompile python3.7.0. The version of openssl installed by yum is relatively low.

2.3 Upgrade openssl
# 1. download openssl
wget https://www.openssl.org/source/openssl-1.1.1a.tar.gz
tar -zxvf openssl-1.1.1a.tar.gz
cd openssl-1.1.1a
# 2.Compile and install
. /config –prefix=/usr/local/openssl no-zlib #no-zlib
make
make install
# 3.Back up the original configuration
mv /usr/bin/openssl /usr/bin/openssl.bak
mv /usr/include/openssl/ /usr/include/openssl.bak
# 4. New version configuration
ln -s /usr/local/openssl/include/openssl /usr/include/openssl
ln -s /usr/local/openssl/lib/libssl.so.1.1 /usr/local/lib64/libssl.so
ln -s /usr/local/openssl/bin/openssl /usr/bin/openssl
# 5. Modify the system configuration
## Write the search path of the openssl library file
echo “/usr/local/openssl/lib” >> /etc/ld.so.conf
## To make the modified /etc/ld.so.conf take effect
ldconfig -v
# 6. Check the openssl version
openssl version

openssl version note:

/usr/local/openssl/bin/openssl: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory

If your libssl.so.1.1 file is under /usr/local/openssl/lib/, you can do this

ln -s /usr/local/openssl/lib/libssl.so.1.1 /usr/lib64/libssl.so.1.1

ln -s /usr/local/openssl/lib/libcrypto.so.1.1 /usr/lib64/libcrypto.so.1.1

3.3 reinstall python
./configure –prefix=/usr/local/python3 –with-openssl=/usr/local/openssl
make
make install

Python Error-TypeError:takes 2 positional arguments but 3 were given

Error:

Today, when I write a simple Python class definition code, I encountered the problem of reporting an error: typeerror: drive() takes 2 positional arguments but 3 were given

The code is as follows

class Car:
    speed = 0
    def drive(self,distance):
        time = distance/self.speed
        print(time)

bike = Car()
bike.speed=60
bike.drive(60,80)

After investigation, it was found that it was the self parameter in the def drive (self, distance) method in the class definition

Now let’s take a brief look at the basic information of self in Python

self , which means that the created class instance itself and the method itself can bind various attributes to self, because self points to the created instance itself. When creating an instance, you can’t pass in empty parameters. You must pass in parameters that match the method, but you don’t need to pass in self. The Python interpreter will pass in instance variables by itself

so there are two solutions

method 1: transfer only one parameter. If you want to transfer two parameters, look at method 2

class Car:
    speed = 0
    def drive(self,distance):
        time = distance/self.speed
        print(time)

bike = Car()
bike.speed=60
bike.drive(80)

Method 2:

class Car:
    speed = 0
    def drive(self,distance,speed):
        time = distance/speed
        print(time)
bike = Car()
bike.drive(80,50)

Problem typeerror:__ init__() Take 1 positive argument but 2 were given solution

When building the automation framework, I encountered a problem, as shown in the following figure:

According to the meaning of the error, it should be the problem of the __init__ function, and the location should be the HomePage file.
Go and check the file immediately, as shown in the figure:

It turned out to be careless __init__ (self)
after passing in one less parameter driver , you still have to be careful

Solution:
def init (self, driver): just add the parameter driver

 

[Solution] systemerror: the solution of parent module ” not loaded, cannot perform relative Import

Defect: __mian__ cannot use relative import

PEP 328 Relative Imports and __name__ states:

Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to ‘__main__’) then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

That is: relative import in the package hierarchy, use the __name__ attribute of the module to get the location of the module. But if the name of the module does not contain any package information (for example, __main__ module), regardless of whether the module is actually located in the file system, relative imports will be imported as a top level module.

repair

According to the recommendations of 6.4.2. Intra-package References :

Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.

__mian__ use Absolute importmanner, while still using other modulesRelative Import

if __name__ == '__main__':
   sys.path.append(os.path.dirname(sys.path[0]))

Import method

Refer to stackoverflow vaultah’s answer, which is more detailed, so I won’t repeat it here.

 

Why choose the advantage of relative import

PEP 328 Rationale for Relative Imports states:

Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages.In addition, a module inside a package can’t easily import itself without relative imports.

That is: relative import can rebuild large python packages without re-editing sub-packages; in addition, relative import can import itself relatively easily.

 

Python3.x Run Python2.x Codes syntax error: “Missing parentheses in call to ‘print’

#Another type of error
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(

The format of the code is as follows:

print "File %s not exist" % filename
。。。
print '-------xxx------'

change to 
print ("File %s not exist" % filename)
print ('-------xxx------')

Link: https://stackoverflow.com/questions/41341149/python-3-6-0-syntax-error-missing-parentheses-in-call-to-print?noredirect=1&lq=1