Relative Content

K4NZDROID

category

「Python」- setuptools (easy-install)

卸载使用 setup.py 安装的应用
python setup.py uninstall – Stack Overflow

python setup.py install –record files.txt
xargs rm -rf < files.txt

参考文献
Building and Distributing Packages with Setuptools — setuptools 54.1.0 documentation[……]

READ MORE

「Python」- 同时运行多个不同版本:虚拟环境(学习笔记)

问题描述
在开发 Python 应用时,应用程序经常需要运行在不同版本的环境中、安装不同版本的模块,但是这些模块是相互冲突的、无法共存的。比如,某些 Python 项目运行在 django 2.0 中,而某些 Python 项目运行在 django 3.1 中,我们无法在系统中同时安装两个版本的 django 模块。但是,这是常见需求,很多编程语言都需要面对类似的问题,那要怎么办呢?
在 Python 中,我们可以使用虚拟环境(Virtual Environments)来解决该问题。
该笔记将记录:在 Python 中,如何使用虚拟环境(Virtual Environments)来运行多个不同版本(且独立的)Python 环境,以解决多个项目需要不同版本 Python 环境的问题。
解决方案
虚拟环境(Virtual Environments)
在 Python 中,虚拟环境(Virtual Environments)就是该问题的解决方案。在创建虚拟环境后,相关操作将发生在该环境中(这里“相关操作”是指与 Python 环境有关的操作,比如 pip install 将会将模块安装到该虚拟环境中,而不会影响系统环境),使得单个项目的运行环境与其它项目独立起来。
如下步骤,搭建虚拟环境:

# 第一步、安装 virtualenv 模块
pip3 install virtualenv

# 第二步、创建虚拟环境
virtualenv –python=python3 “venv-example” # 执行该命令,将创建 ./venv-example 目录

# 第三步、激活虚拟环境
source venv-example/bin/activate # 执行该命令后,我们将进入虚拟环境

# 第四步、执行操作
# 与 Python 环境有关的所有操作将发生在该环境中
# 比如,模块安装将安装到 venv-example 下的对应目录中,并在使用时从中加载模块。

# 退出当前虚拟环境
deactivate

virtualenvwrapper – 管理虚拟环境
使用 virtualenv 存在的一个问题是:为了运行不同应用,我们需要为每个应用单独创建虚拟环境。但是,很多应用需要的虚拟环境是相同的,这些完全应用可以共享虚拟环境。因此,我们可以写个工具,用于创建多个虚拟环境,并且能够在这些虚拟执行快速切换。
所幸,现在已经有了这个工具,使用 virtualenvwrapper 工具,便可解决该问题。在安装该工具后,通过命令 mkvirtualenv 将在“共享目录”中创建虚拟环境,通过命令 workon 快速加载特定虚拟环境,当然还有其他功能。
安装并使用 virtualenvwr[……]

READ MORE

「Python」- 访问数据库

问题描述
该笔记将记录:在 Python 中,如何操作常见数据库;
MongoDB
该部分将介绍访问 MongoDB 数据库的方法。在示例中,我们使用 PyMongo 模块:
我们使用 PyMongo 客户端,安装:

#!/bin/sh

pip3 install pymongo

访问项目仓库:http://github.com/mongodb/mongo-python-driver
访问官方文档:https://api.mongodb.com/python/current/api/index.html

我们主要使用 pymongo 文档:https://api.mongodb.com/python/current/api/pymongo/index.html

最常使用 MongoClient 对象:https://api.mongodb.com/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient

下面只进行简短地介绍,更多内容请参考官方文档;[……]

READ MORE

「Python」- 字符串编码与解码

解决方案
base64

#!/usr/bin/python3

import base64

coded_string = ”’Q5YACgA…”’
plain_text = base64.b64decode(coded_string)

参考文献
Python base64 data decode – Stack Overflow[……]

READ MORE

「Python」- HTTP(s)

内容简介
整理发送HTTP(s)请求的库(只因urlib难以记忆)。
Requests: HTTP for Humans
https://requests.readthedocs.io/en/master/
https://github.com/psf/requests/ 12/25/2019 Star 41.1k
使用基础认证

requests.get(‘https://example.com/user’, auth=(‘username’, “password”))

在请求中提交 XML 数据

requests.get(
‘https://example.com’,
headers={‘Content-Type’: ‘application/xml; charset: utf-8’},
data=”<xml_string>”
)

urllib3
https://urllib3.readthedocs.io/en/latest/
https://github.com/urllib3/urllib3 12/25/2019 Star 2.2k
参考文献
Python’s Requests Library (Guide) How can I send an xml body using requests library?[……]

READ MORE

「Python」- JSON、YAML、YAML(常用数据格式操作)

JOSN
How to count items in JSON data Using JSON config files in Python
本文将整理:在 Python 中常用 JSON 操作。

import json

# 字典 => 字符串,顺便美化输出
json_string = json.dumps({
“result”:[{“find”: “true”}]
}, indent=2)

# 字符串 => 字典
json_object = json.loads(json_string)

# 文件 => 字典
json_ojbect = json.load(open(“/path/to/file.txt”))

# 求长度
len(json_object)

XML
xml.etree.ElementTree — The ElementTree XML API Python xml ElementTree from a string source?
在 Python 中,与 XML 有关的操作,以及相关问题的解决办法。

# 导入模块
import xml.etree.ElementTree as ET

# 读取XML数据
tree = ET.parse(“/path/to/foo.xml”)
tree = ET.fromstring(xml_string)

# 修改数据
for item in tree.iter(“item”):
item.text = “some text”

tree.write(“/path/to/bar.xml”)

# 打印XML数据
xml_string = tree.tosting()[……]

READ MORE

「Python」- 输出日志

问题描述
该笔记将记录:在 Python 中,如何进行日志打印,以及常见问题处理。
解决方案
简单示例:

import logging
logging.basicConfig(encoding=’utf-8′, level=logging.DEBUG)
logging.debug(‘This message should go to the log file’)
logging.info(‘So should this’)
logging.warning(‘And this, too’)
logging.error(‘And non-ASCII stuff, too, like Øresund and Malmö’)

彩色日志打印:

#!/usr/bin/python3

# pip install coloredlogs

# 简单示例
import coloredlogs, logging
coloredlogs.install()
logging.info(“It works!”) # 2014-07-30 21:21:26 peter-macbook root[7471] INFO It works!

# 特定 Logger 设置
logger = logging.getLogger(__name__)
coloredlogs.install(level=’DEBUG’, logger=logger) # a specific logger object

logger.debug(“this is a debugging message”)
logger.info(“this is an informational message”)
logger.warning(“this is a warning message”)
logger.error(“this is an error message”)
logger.critical(“this is a critical message”)

参考文献
Logging HOWTO — Python 3.9.2 documentation How can I color Python logging output? – Stack Overflow xolox/python-coloredlogs: Colored terminal output for Python’s logging module[……]

READ MORE

「Qt」

内容简介
本部分整理与Qt相关的内容。但是目前Python是我的主要方向,所以本部分的绝大多数内容都是与Qt的Python API相关的技术。也会涉及一些Qt的基本概念,毕竟基础原理是要懂得。
参考文献
Wikipedia/Qt (software) GitHub/Qt[……]

READ MORE

「PyQt5」- signals and slots

内容简介
本部分介绍在Python的Qt中如何处理信号与槽。
基本概念
# Slot
响应于特定信号而被调用的函数,所以本质上还是函数。在Qt中的Widget有许多预定义的slot,但通常的做法是将Widget子类化,并添加自己的slot,以便可以处理感兴趣的信号。
# Signal
当对象的内部状态发生更改时,对象会发出Signal。Signal是公共访问函数,所以说Signal还是函数,可以从任何地方发出,但官方建议只从定义信号及其子类的类中发出。
简单示例
下面是一个及其简单的示例:

# 在按钮点击的时候,触发内部的slot_method方法
# 行话:clicked信号被连接到slot_method槽。当发出clicked信号时,将执行slot_method方法。
m_button.clicked.connect(self.slot_method)

参考文献
PyQt5 signals and slots Support for Signals and Slots Qt 5.13 / Qt WebEngine / C++ Classes / QWebEngineView PySide/PyQt Tutorial: Creating Your Own Signals and Slots PyQt – Signals & Slots Qt 5.13 / Qt Core / Signals & Slots[……]

READ MORE

「Qt」- PyQt and PySide

内容简介
本部分简单介绍与PyQt及PySide这两个库的区别,以及相关的内容。
# Qt for Python (PySide2)
简述
「Qt for Python」是一个项目,由Qt官方提供,它提供Qt的Python绑定,可以使用Python语言创建Qt程序。
安装
如果要在Python中使用「Qt for Python」项目,则安装PySide2模块即可。
教程
Python Qt tutorial
PyQt – PyQt4 for Qt v4 / PyQt5 for Qt v5
简述
与「Qt for Python」作用类似,向Python中暴露Qt接口,可以使用Python语言开发Qt应用程序。
安装
如果要在Python中使用PyQt模块,则安装PyQt4或者PyQt5模块即可,并且还包含一些其他的模块,可能需要单独安装。比如安装「WebEngine」模块,执行pip install PyQtWebEngine=5.13.0命令,同时它也会安装PyQt5等相关的模块。
教程
Qt for Python/Tutorial
文档
PyQt v5.13 Reference Guide
对比总结
在WebEngine方面,与PyQt5相比,PySide2覆盖的API较少,因此在进行WebEngine编程时,推荐使用PyQt5模块。
参考文献
Qt for Python – The official Python bindings for Qt. What is PyQt?[……]

READ MORE

「Qt」- QApplication, QGuiApplication and QCoreApplication

内容简介
本文简单整理QApplication, QGuiAppication, QCoreApplication这三个对象之间的区别。
# QCoreApplication
基类。在命令行应用程序中,应该使用它。
# QGuiApplication
基类 + GUI功能。在QML应用程序中,应该使用它。「QML」是一种用户界面标记语言,是一种指令使的语言,与CSS有些相似。
# QApplication
基类 + GUI + 对Widget支持。在QtWidgets应用程序中,应该使用它。
# Event loop
字面上翻译就是「事件循环」,详细的解释需要阅读文档和一些Qt相关的书籍。但简而说:事件循环是一个无限循环,它在应用程序的后台运行,处理从操作系统传入的事件(鼠标移动,点击,绘制事件,硬件事件等)以及内部通信(信号和插槽)。调用app.exec()时,事件循环开始,这也是“在执行app.exec()后,后续代码不会再继续执行”的原因。
参考文献
differences between QApplication, QGuiAppication, QCoreApplication classes[……]

READ MORE

「Qt」- WebKit and WebEngine

内容简介
本部分介绍QtWebKit以及QtWebEngine相关的技术。但是,本文更侧重于QtWebEngine技术,因为在Qt5.6中移除了QtWebKit模块。
另外,本部分的内容更侧重于爬虫,因为这些技术是在写爬虫的时候才学习的(反爬虫技术再牛,也得让用户可以正常访问,不是么?那……我们就做一个正常的用户)。
# QtWebKit and Qt WebEngine
根据官方所述「QtWebKit got deprecated upstream in Qt 5.5 and removed in 5.6」,所以从后面开始,我们整体基于QtWebEngine展开,极少涉及与QtWebKit相关的技术。
# 官方文档
不管是PyQt还是PySide模块,它们的文档都不够详尽。而PySide的文档明显是从Qt的文档里复制过来的。
如果要使用这些API库:「详细描述」还要参考Qt官方文档,但是「函数参数类型」可以参考这些文档。
Qt for Python/WebEngine
PySide2.QtWebEngineWidgets

Qt WebEngine Debugging and Profiling
# PyQt5
PyQt v5.13 Reference Guide / QtWebEngineWidgets
# 使用WebEngine构建应用

import sys
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)

web = QWebEngineView()
web.load(QUrl(“https://www.example.com”))
web.show()

sys.exit(app.exec())

附加说明
# Get Html element value with QWebEngine 在QtWebEngine中,如果要获取页面的元素,需要通过QWebEnginePage的runJavaScript方法。
# Missing methods for QWebEnginePage with QWebEngineCallback 在PySide2中,没有toHtml方法。
相关示例
# WebEngine Quick Nano Browser 使用QML语言创建一个浏览器。
# WebEngine Content Manipulation Example 向页面中注入JQuery[……]

READ MORE

「Qt」- 杂记

内容简介
本部分整理与Qt有关的杂记。
# Qt Creator 、Qt Designer、Qt Quick Designer
-「Wikipedia/Qt Creator#Editors」 -「Qt Designer vs Qt Quick Designer vs Qt Creator?」
Qt Creator是Qt的IDE,它大大简化了Qt的开发。
Qt Designer是一个图形工具,可以让您构建QWidget GUI。
Qt Quick Designer与Qt Designer类似,但用于构建基于QML的GUI。
Qt Quick Designer与Qt Designer两者都内置于Qt Creator。
# 安装Qt Creator工具

#!/bin/sh

################################################################################
# Kali GNU/Linux Rolling
#
# # Ubuntu 14.04 QtCreator Qt5 examples missing
# # https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
# # Getting Started With Qt and Qt Creator on Linux
# # https://www.ics.com/blog/getting-started-qt-and-qt-creator-linux
#
################################################################################
# 安装基础
apt-get install qtcreator

# 安装示例(不同的示例可能在不同的包中),该命令并未安装说有的示例包。
apt-get install qtbase5-examples qtbase5-doc-html qtwebengine5-examples

# 使TabWidget按钮居中
-「QTabwidget’s tab text alignment not working」

# 创建按钮
QLabel * button = new QLabel(“text”);
button->setAlignment(Qt::AlignLeft);

# 将原有的文本置空
ui->tabWidget->tabBar()->setTabText(index, “”);

#[……]

READ MORE

「PYTHON」- Paramiko:连接 SSH 服务

Paramiko 是 Python 实现 SSHv2 协议的模块,它支持口令认证和公钥认证两种方式。我们能够基于Paramiko模块编写Python代码,实现SSH相关功能。
它可以实现安全的远程命令执行、文件传输等功能。
组件架构(架构概述)
Paramiko 组件如下图所示,最常用的两个类为 SSHClient 类和 SFTPClient 类,分别提供 SSH 和 SFTP 功能。
我们将主要学习四个类的相关方法:Transport类,Key handling类,SSHClient类,SFTPClient类;
常用协议类

Channel:该类用于创建在 SSH Transport 上的安全通道。Channel类包含执行命令,请求X11会话,发送数据,打开交互式会话等方法。通常这些来自Channel类的常用方法已包装在 SSHClient 中。
Message:SSH Message是字节流,该类包含向流中写入字节,提取字节等方法。该类对字符串、整数、bools、无限精度整数(Python中称为long)的某些组合进行编码。
Packetizer:数据包处理类。Packetizer类包含检查握手,获取channel ID等方法。
Transport:该类用于在现有套接字或类套接字对象上创建一个Transport会话对象。Transport类包含公钥认证,打开channel通道等方法。
SFTPClient:该类通过一个打开的SSH Transport会话创建SFTP会话通道并执行远程文件操作。SSHClient类包含建立连接,打开交互式会话等方法。
SSHClient:SSHClient类是与SSH服务器会话的高级表示。该类集成了Transport,Channel和SFTPClient类。SFTPClient类包含文件上传,文件下载等方法。
密钥相关类

SSH Agent类:该类用于SSH代理。
Host keys类:该类与OpenSSH known_hosts文件相关,用于创建一个host keys对象。
Key handling类:该类用于创建对应密钥类型的实例,如RSA密钥,DSS(DSA)密钥。
Transport 及其方法介绍
一个SSH Transport连接到一个流(通常为套接字),协商加密会话,进行认证。后续可在加密会话上创建通道。多个通道可以在单个会话连接中多路复用(事实上经常如此,如端口转发)。
如下为方法示例:

tran = paramiko.Transport((‘192.168.56.100’,22))
tran.connect(username=‘client’,p[……]

READ MORE

「Python」- 解析命令行参数

问题描述
在编写 Python 工具时,我们经常需要解析命令行参数,以获取输入数据。
该笔记将记录:在 Python 中,如何解析命令行参数的方法(比如,使用模块 getopt 解析命令行参数),以及相关问题处理。
解决方案
通过 argparse 模块

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(“–host”, default=”0.0.0.0″, help=”Exporter listen address”)
parser.add_argument(“–port”, default=”9349″, help=”Exporter listen port”)
args = parser.parse_args()

print ‘Query string:’, args

注意事项:在 Python 2.7- 中,使用 optparse 模块。
通过 getopt 模块
使用示例:

import getopt, sys

try:
opts, args = getopt.getopt(sys.argv[1:], “hc:”, [“help”,”config-file=”])
except getopt.GetoptError:
print(“error message”)
sys.exit(1)

for opt, arg in opts:
if opt == “-h”:
# doing some stuff
elif opt in (“-h”, “–config-file”):
# doing some stuff
else:
# doing some stuff

参考文献
Python 命令行参数 python – What’s the best way to parse command line arguments? – Stack Overflow Argparse Tutorial — Python 3.9.2 documentation python – Argparse: Required arguments listed under “optional arguments”? – Stack Overflow[……]

READ MORE

「Python」- 框架,Django,学习笔记,开始开始

问题描述
该笔记将记录:在学习 Django 过程中而产生的学习笔记,以及相关问题的解决办法。
解决方案
参考 Django/Writing your first Django app, part 1 文档,我们开始进行 Django 的初识与学习。
针对该笔记及其子章节,其主要内容是对官方文档的学习与摘率,包括相关问题的解决方案。
P1 创建应用的基本步骤
python – How to check Django version – Stack Overflow FAQ: Installation | Django documentation | Django windows – Django, can’t create app in subfolder – Stack Overflow
参考 Writing your first Django app, part 1 文档,以进行快速入门,通过该文档能够让我们对整个框架的 使用方法、目录结构、路由模式、运行方法 形成基础认识。
创建项目(PROJECT),创建应用(APPLICATION),运行服务,获得能够快速访问的 Web 应用;

// —————————————————————————- # 版本选择

Django version Python versions
2.2 3.5, 3.6, 3.7, 3.8 (added in 2.2.8), 3.9 (added in 2.2.17)
3.0 3.6, 3.7, 3.8, 3.9 (added in 3.0.11)
3.1 3.6, 3.7, 3.8, 3.9 (added in 3.1.3)
3.2 3.6, 3.7, 3.8, 3.9, 3.10 (added in 3.2.9)
4.0 3.8, 3.9, 3.10

// —————————————————————————- # 第一步、安装框架

# pip3 install Django==3.2.13 # 我们当前使用的版本

# python3 -m django –version # 查看当前安装版本

# ./manage.py –version[……]

READ MORE

「Django」- 视图、模板、学习笔记

解决方案
参考 Writing your first Django app, part 3 文档,以获取在 Django 中使用视图及模板的方法。
在 views.py 中: 进行相关的业务逻辑处理, 并使用 HttpResponse() 来显示页面,或使用 render() 来显示页面; 通过 Http404() 或 get_object_or_404() 进行相关错误处理;
在 template/<app-name>/ 中,添加相关模板文件; 并在模板文件中使用模板语言来显示页面; 通过 url() 的 name 参数定义的名称来引用地址,以防止硬编码; 通过命名空间的方式来定义和引用 URL 防止出现命名冲突的情况;
常见问题
注入变量到所有模板
python – Django – How to make a variable available to all templates? – Stack Overflow

1)Add custom_app to INSTALLED_APPS in settings.py (you’ve done it already, right?);

2)Create a context_processors.py into custom_app folder;

3)Add the following code to that new file:

def categories_processor(request): # request 参数是必须的
categories = Category.objects.all()
return {‘categories’: categories}

4)Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py

TEMPLATE_CONTEXT_PROCESSORS += (“custom_app.context_processors.categories_processor”, )

5)And now you can use {{categories}} in all the templates

关闭 HTML 转义
django – Rendering a template variable as HTML – Stack Overflow

// 默认 HTML 转义,我们需要关闭 HTML 转义;

{{ myhtml |safe }}

{% autoescape o[……]

READ MORE

「Django」- 配置管理,设置(Setting)

问题描述
当应用程序的运行时,需要指定不同的配置信息或参数,以来控制应用程序的运行。
该笔记将记录:在 Django 中,如何管理配置文件;
解决方案
在 Django 中,通过 Django settings 来完成应用程序的应用控制:
参考官方文档,以获取通过配置文件来控制系统运行的方法: 1)2.2 / Settings 2)4.0 / Settings | Django documentation | Django
补充说明
除此之外,也能够通过其他模块来进行配置处理,例如 ConfigParser 模块:

# https://stackoverflow.com/questions/12750778/booleans-in-configparser-always-return-true
print config.getboolean(‘main’, ‘some_boolean’)

但非 Django 内置的配置方法不是我们关注的重点,我们更倾向于使用框架内置的工具和方法。
配置文件管理方法
python – Is this approach to Django multiple settings files reasonable? – Stack Overflow Django Tips #20 Working With Multiple Settings Modules
如上文档,提到多种配置文件的管理方法。如下是我们从其中借鉴方法:

settings
├── __init__.py
├── defaults.py
├── dev.py
└── production.py

// —————————————————————————- // settings/__init__.py

from dev import *

// —————————————————————————- // settings/dev.py

# Load defaults in order to then add/override with dev-only settings
from defaults import *

DEBUG = True
# … etc.

// —————————————————————————- // settings/produc[……]

READ MORE

「Python」- 框架,Flask,学习笔记

问题描述
我们经常使用 Python 语言,但是多半是用作批处理和脚本任务,从未写过任何 Web 应用,这可能与我们的工作内容相关。
现在,我们需要使用 Flask 编写应用(实际上是有个项目是 Flask 框架开发的,现在我们需要修改这个项目),所以要开始学习新技术,Flask 框架。
该笔记将记录:使用 Flask 框架编写应用的示例(入门级)以及常见问题处理,后续将不断的补充相关内容。
解决方案
入门的简单示例
官方首页给的示例也是相当简单的,但是足以说明问题,我们很快就能得到能够运行的 Web 应用:
编写 helloworld.py 文件:

from flask import Flask, escape, request

app = Flask(__name__)

@app.route(‘/’)
def hello():
name = request.args.get(“name”, “World”)
return f’Hello, {escape(name)}!’

if __name__ == “__main__”:
app.run(debug=True)

然后,运行该应用:

# python /tmp/demo.py
* Serving Flask app “demo” (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 249-201-688

最后,访问该应用程序:

# curl http://127.0.0.1:5000/
Hello, World!

参考文献
Flask | The Pallets Projects[……]

READ MORE

「Python」- 代码片段

作为一个Python菜鸡,有些常用的代码和方法还是要整理一下的:

#!python3

################################################################################################################################################################
# 多行代码可以使用反斜线,一种经典的做法
################################################################################################################################################################

################################################################################################################################################################
# 打印字典或者数组什么的
# https://stackoverflow.com/questions/15785719/how-to-print-a-dictionary-line-by-line-in-python
################################################################################################################################################################
print(json.dumps(dicObject, indent = 4, ensure_ascii=False)) # 并显示UNICODE字符,而不时是转义序列

################################################################################################################################################################
# Python String endswith() Method
# https://www.tutorialspoint.com/python/string_endswith
###################################[……]

READ MORE

「Python」- 获取操作系统相关信息

获取网络信息
Python Get Default Gateway IP Using Netifaces: A Step Guide – Python Tutorial python – How to get the physical interface IP address from an interface – Stack Overflow

pip install netifaces

import netifaces

获取网关设备及地址:

# gets gateway of the network
gws = netifaces.gateways()
gateway = gws[‘default’][netifaces.AF_INET][0] # 默认网关地址
gateway_interface = gws[‘default’][netifaces.AF_INET][1] # 默认网关接口名称

获取网卡的地址:

address = netifaces.ifaddresses(“interface_name”)[netifaces.AF_INET][0][‘addr’][……]

READ MORE

「Python」- 错误汇总

问题描述
对开发中遇到的错误进行汇总。
TypeError: ‘module’ object is not callable
问题描述:在 Dajngo 中,我们遇到该错误。注意,还有很多其他原因会到导致该问题。
原因分析:我们使用的 Django 不支持更新的 Celery 版本,进而 Celery 注解导致该错误。
解决方案:Celery 版本降级,指用 Django 支持的版本;
# file=sys.stderr)

File “/usr/lib/python3.5/site.py”, line 182
file=sys.stderr)
^
SyntaxError: invalid syntax

版本:Python3.5 描述:在Python3.5脚本中使用os.system调用了一个python2.7的命令,产生了如上错误。是在Eclipse中直接运行Python3.5脚本。 解决:抱着试一试的态度,我在终端中直接运行了脚本,是正常的,没有上述错误。难道是Eclipse导致的BUG?在Eclipse中安装了PyDev插件。
ImportError: No module named ‘encodings’
python – ImportError: No module named ‘encodings’ – Stack Overflow
问题描述
在执行虚拟环境时,出现如下错误:


Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named ‘encodings’

原因分析
我们原本使用 Python 3.7 创建虚拟环境,迁移到使用 Python 3.9 新主机而出现该错误。
我们没有找到具体原因,我们推测是因为新环境缺少某些模块。
解决方案
我们将重建虚拟环境: 1)pip freeze > requirements.txt 2)然后,使用 virtualenv 重新基于 Python 3.9 的创建虚拟环境,并激活; 3)pip install -r requir[……]

READ MORE

「Python」- bad magic number in xxx

内容简介
处理ImportError: bad magic number in ‘xxxx’错误。
问题描述
执行Python脚本,提示ImportError: bad magic number in ‘xxxx’错误。
问题原因
在项目中包含一些.pyc文件,这其中包含了一些之前的版本信息和日期时间。删除这些文件即可。
解决办法
在项目的根目录中执行:

#!/bin/sh

find . -name “*.pyc” -exec rm -f {} \;

参考文献
ImportError: bad magic number in ‘time’: b’\x03\xf3\r\n’ in django[……]

READ MORE

「Python」- module object is not callable

内容简介
处理TypeError: ‘module’ object is not callable错误。
问题描述
运行脚本产生TypeError: ‘module’ object is not callable错误。
问题原因
没有区分清除“模块名”与“类名”。模块名是模块名,类名是类名,二者是有所区别的。
在import时,导入的是类名,而不是模块名,应该是import <module_name>.<class_name>或者from <module_name> import <class_name>的形式,而单独引入模块(import <module_name>)是不可以的,模块不可以调用。
解决办法
修改导入语句,引入类名。
参考文献
TypeError: ‘module’ object is not callable[……]

READ MORE

「PyPy」- No module named xxx

内容简介
处理ImportError: No module named xxx错误。
问题描述
执行pypy wxwork-notify.py时产生如下错误:

Traceback (most recent call last):
File “wxwork-notify.py”, line 7, in <module>
import simplejson
ImportError: No module named simplejson

系统环境

操作系统:
Kali GNU/Linux Rolling

问题原因
在Python中,出现类似问题通常是由于模块没有安装,那解决该问题的方法就是安装对应的模块。
但是,我遇到的问题并不是模块未未安装。因为运行python wxwork-notify.py命令是正常的,只有使用pypy时是错误的。
之所以出现该问题,是因为有些东西我不清楚,没有了解到。在PyPy中,它有自己的site-packages路径,因此需要为PyPy单独安装模块,或者单独安装pip命令来安装其他模块。
解决办法

#!/bin/sh

apt-get install pypy-setuptools

参考文献
PyPy: “ImportError: No module named xlrd”[……]

READ MORE

「jq」-

功能简述
命令行中的 JSON 处理器
常用命令
输出多个字段(使用自定义格式):

echo ‘<JOSN STRING>’ | jq ‘.item[] | .f1 + ” ” + .tags[].f2’

输出多个字段(使用 TSV 格式):

echo ‘<JOSN STRING>’ | jq ‘.item[] | [.f1, .tags[].f2] | @tsv’ # 制表符分隔

对字段名中的进行转义处理:

echo ‘<JOSN STRING>’ | jq ‘.item[] | .data.[“tls.crt”]’

语法格式

jq [options…] filter [files…]

命令描述
jq can transform JSON in various ways, by selecting, iterating, reducing and otherwise mangling JSON documents. For instance, running the command jq ´map(.price) | add´ will take an array of JSON objects as input and return the sum of their “price” fields.
jq can accept text input as well, but by default, jq reads a stream of JSON entities (including numbers and other literals) from stdin. Whitespace is only needed to separate entities such as 1 and 2, and true and false. One or more files may be specified, in which case jq will read input from those instead.
The options are described in the INVOKING JQ section; they mostly concern input and output formatting. The filter is written in the jq language and specifies how to transform the input file or document.
命令选项
jq filters run on a s[……]

READ MORE

「Virtualization and Emulator」

计算机虚拟化技术属于计算机科学专业,具体来说,属于计算机体系结构或操作系统等相关专业方向。虚拟化技术是计算机科学领域中的一种技术,它涉及到计算机硬件、操作系统和应用程序等多个方面的知识,需要对计算机系统的整体架构和工作原理有深入的理解。因此,学习虚拟化技术需要具备计算机科学相关的知识背景和技能。
相关链接
Wikipedia/Hypervisor
Docker学习总结之Docker与Vagrant之间的特点比较
Hypervisor
Hypervisor:是一种运行在物理服务器和虚拟机操作系统之间的中间软件层,可允许多个操作系统和应用共享一套基础物理硬件。因此也可以看作是虚拟环境中的“元”操作系统,它可以协调访问服务器上的所有物理设备和虚拟机,也叫虚拟机监视器(Virtual Machine Monitor VMM)。Hypervisor是所有虚拟化技术的核心。目前主流的Hypervisor有KVM,VMWare ESXi,Xen,HyperV等。 HyperV
Xen and Xen Server
VPC – Virtual Private Cloud
Vagrant https://www.vagrantup.com/ 一个基于Ruby的工具,用于创建和部署虚拟化开发环境。它使用Oracle的开源VirtualBox虚拟化系统。
MONO 在Ubuntu操作系统上安装mono的具体方法 https://www.linuxdot.net/bbsfile-3090
参考文献
oVirt和OpenStack的区别[……]

READ MORE

「Windows」- Subsystem for Linux,WSL

问题描述
WSL:在 Windows 中,使用 GNU Linux 工具的方法。
该笔记将记录:在 Windows 中,如何使用 WSL 模块,以及相关问题的解决方法。
注意事项
# 09/13/2021
我们需要在笔记本中运行 VirtualBox 5.2 版本,但是 VirtualBox 与 Hyper-V 不能共存: 1)如果开启 Hyper-V 模块,那么 VirtualBox 将提示 VT-x is not available 错误; 2)如果关闭 Hyper-V 模块,那么 WLS 2 将提示 The specified network name is no longer available 错误;
鉴于 VirtualBox 能够将 主机文件系统挂在到 虚拟机中,所以能够在 Linux 环境下进行操作。这能够满足我们的需求,所以我们放弃使用 WSL 2 特性。
安装 WSL 模块
参考 Windows Subsystem for Linux Installation Guide for Windows 10 文档。
安装步骤: 1)在 Control Panel ⇒ Programs ⇒ Turn Windows features on or off 中, 2)启用 Windows Subsystem for Linux 选项,并重启主机; 3)在 Microsoft Store 中,搜索并安装 Ubuntu 20.04 TLS 发行版;
在安装完成后,Windows Terminal 能够快速进入 Ubuntu 20.04 中(如果需要设置,参考 Install and set up Windows Terminal 文档)
常用操作
查看当前 WSL 运行版本
WSL: Am I running version 1 or version 2?

# wsl -l -v
NAME STATE VERSION
* Ubuntu Stopped 1

挂载新磁盘
How to Mount Windows Network Drives in WSL
当主机插入 U 盘或者其他磁盘设备后,需要挂载到 WSL 中:

mount -t drvfs M: /mnt/m

常见问题处理
The specified network name is no longer available.(指定的网络名不再可用)
WSL 2 FAQs
原因分析,正如 Microsoft 官方 FAQ 所说:

Will I be able to[……]

READ MORE

「Windows Virtual PC and XP Mode」

Windows Virtual PC
引自百度百科对 Windows Virtual PC 的介绍:

Windows Virtual PC 是 Microsoft 最新的虚拟化技术。借助 Windows Virtual PC,您单击一次即可直接从基于 Windows 7 的计算机在虚拟的 Windows 环境中运行许多生产应用程序。

是不是“最新的虚拟化技术”,咱不知道。反正运行 XP Mode 需要安装该工具。
第一步、安装 Windows Virtual PC 工具
访问官网下载 Windows Virtual PC 工具。
第二步、安装 XP Mode 工具
访问官网下载 Windows XP Mode 工具。
第三步、启动并设置 XP Mode 工具
Start => Windows Virtual PC => Windows XP Mode
参考文献
百度百科/Windows Virtual PC How to install and use Windows XP Mode in Windows 7[……]

READ MORE