开始flask001

flask虚拟环境

根据flask官网介绍,使用虚拟环境来管理项目的依赖,包括开发与生产环境。

因为随着Python项目增多,很有可能要与不同的python库、甚至不同版本的python打交道。一个项目的新版本库文件与另外一个项目可能不兼容。

虚拟环境独立于python库,一个虚拟环境匹配一个项目。为一个项目安装的包不会影响其他项目包或系统包。

Python绑定venv模块来创造虚拟环境。

创建虚拟环境

macOS/Linux

$ mkdir flaskproject
$ cd flaskproject
$ python3 -m venv venv

激活虚拟环境

macOS/Linux

$  . venv/bin/activate

这里需要注意,这个“.”和venv之间要有空格,参见stackoverflow的解释:

. venv/bin/activate

or

source venv/bin/activate

使用虚拟环境,并设置为开发环境

在venv环境下,如果直接启动flask服务:

flask run

会有如下红色警告信息,因为flask默认开发者是生产环境下工作,而开发环境不稳定,所以会提示如下告警。
Screen Shot 2021-12-20 at 12.00.48 AM

因此需要进行设置

(venv) MDMacPro/Users/XXXXXXXXXXXX/flaskr/flaskproject/bmi[23:58]export FLASK_ENV=development

参考flask设置环境变量

使用git checkout 2a

使用git checkout 2a 把对应project的source code复制到visual studio里面

由于已经通过git启动了相关程序,因此会展示如下内容。

使用git reset –hard

如果对git上的源代码进行了修改,可以使用git reset –hard放弃所有修改

(venv) MDMacPro/Users/madapapa/Study/madapapa.com/flaskr/flaskproject/flaskygit:(32acca2) ✗ [12:07]git reset --hard
HEAD is now at 32acca2 Chapter 2: Dynamic routes (2b)
(venv) MDMacPro/Users/madapapa/Study/madapapa.com/flaskr/flaskproject/flaskygit:(32acca2) [12:09]git checkout 3a
Previous HEAD position was 32acca2 Chapter 2: Dynamic routes (2b)
HEAD is now at e020af8 Chapter 3: Templates (3a)

通过requests库使用基本http命令 第一课

在python里,进行http相关的请求,则requests库是事实标准,这个库将复杂的http请求命令,封装在简单、优美的api里。

简单的request如get、post,当然也可以在此基础上增加鉴权功能,或者通过配置请求来防止应用的速度变慢。

安装与引用requests库

使用pip在python里安装requests库,如果是python3,则是pip3

$ pip install requests

使用requests也很简单,如下

import requests

GET请求

最普通常见的HTTP请求是GET。通过get,你可以获得指定的资源。

requsets.get()

Status Codes

Screen Shot 2021-12-05 at 3.04.38 PM
当status_code返回200时,说明你的请求成功,而且服务器返回了你所请求的数据。


因此可以直接利用response的布尔属性来做一些简单判断,不过这种情况就不一定是返回200了,因为只要返回代码在200~400之间,都认为响应成功,但是不一定返回了消息内容(比如204就是这样)

Screen Shot 2021-12-05 at 1.39.28 PM

对比content,text,json等的类型。

套接字python2和python3不同

编写web应用服务器报,TypeError: a bytes-like object is required, not ‘str’错误。
因为python2和python3的版本有些差异,而python3最重要的新特性也是对文本和二进制数据做了更清晰的区分。

文本用unicode编码,为str类型,二进制数据则为bytes类型

python2的例子

import socket,sys 

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('www.madapapa.com',80))
#code=str.encode('GET /api.json HTTP/1.0\r\n\r\n')
#s.send(code)
s.send('GET /api.json HTTP/1.0\r\n\r\n')

while 1:
    buf = s.recv(1000)
    if not buf:
        break
    sys.stdout.write(buf)

s.close()

在python2的环境下运行,执行结果如下
Screen Shot 2021-11-14 at 2.45.47 PM

python3的例子

import socket,sys 

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('www.madapapa.com',80))
#s.send(str.encode('GET /api.json HTTP/1.0\r\n\r\n'))
s.send('GET /api.json HTTP/1.0\r\n\r\n'.encode())


while 1:
    buf = s.recv(1000).decode()
    #s1 = buf.decode()
    if not buf:
        break
    sys.stdout.write(buf)

s.close()

在默认环境下运行(python3),执行结果如下

附录

套接字

套接字是一套用C语言写成的应用程序开发库,它首先是一个库。主要作用就是实现进程间通信和网络编程,因此在网络应用开发中被广泛使用。

套接字(socket)是一个抽象层,应用程序可以通过它发送或接收数据,可对其进行像对文件一样的打开、读写和关闭等操作。套接字允许应用程序与网络中的其他应用程序进行通信。网络套接字是IP地址与端口的组合。

在Python中可以基于套接字来使用传输层提供的传输服务,并以此进行开发网络应用。实际开发中使用的套接字可以分为三类:流套接字(TCP套接字)、数据报套接字和原始套接字。

流式套接字

流式套接字(SOCK-STREAM)。它提供了一种可靠的、可以进行双向连接的数据传输服务。其实现了数据无差错、无重复的发送。流式套接字自身便内设了流量控制功能。在TCP/IP协议簇中,使用TCP协议来实现字节流的传输,当用户想要发送大批量的数据或者对数据传输有较高的要求时,可以使用流式套接字。

数据报套接字

数据报套接字(SOCK-DGRAM)。它提供了一种不可靠的双向数据传输服务。数据包以独立的形式被发送,不提供可靠性保证。数据在传输过程中可能会丢失或重复,并且不能保证在接收端按发送顺序接收数据。在TCP/IP协议簇中,使用UDP协议来实现数据报套接字。在出现差错的可能性较小或允许部分传输出错的应用场合,可以使用数据报套接字进行数据传输,这样通信的效率较高。

原始套接字

原始套接字(SOCK-RAW)。该套接字允许对较低层协议(如IP或ICMP)进行直接访问,常用于网络协议分析,检验新的网络协议实现,也可用于测试新配置或安装的网络设备。

上述就是套接字的大体知识,对套接字有了一定的了解,我们就可以步入正题了。

TCP套接字

TCP套接字就是上面所说的流式套接字,可以使用TCP协议提供的传输服务来实现网络通信的编程接口。

在Python中可以通过创建socket对象并指定type属性为SOCK_STREAM来使用TCP套接字。

由于一台主机可能拥有多个IP地址,所以作为服务器端的程序,需要在创建套接字对象后将其绑定到指定的IP地址和端口上。

这个端口是指对IP地址的扩展,用于区分不同的服务。

不同的服务通常与相对的端口所绑定。

当服务器收到用户请求时就可以根据端口号来确定到底用户请求的是何种服务。

关于服务于端口的绑定类型,我们会在之后的开发的当中具体描述。

如何用Python设置一个客户端的功能,简易代码如下:

fromsocketimportsocket

def main():

1.创建套接字对象默认使用IPv4和TCP协议

client= socket()

2.连接到服务器 ,指定IP地址和端口

client.connect((‘192.168.1.8’, 1080))

3.从服务器接收数据

print(client.recv(1024).decode(‘utf-8’))

client.close()

if__name__ == ‘main‘:

main()

上述代码就实现了客户端的功能,它可以与服务器进行通信。当然,上述代码只能作为一个最简单的客户端构建方式。更复杂的构建方式,学记将在之后的学习中为大家继续介绍。

Learn to program with Minecraft and Python

http://www.broadview.com.cn/book/156

0.1 https://www.nostarch.com/pythonwithminecraft/
1.1 https://www.nostarch.com/pythonwithminecraft/
1.2 https://minecraft.net/
1.3 https://minecraft.net/download
1.4 http://www.python.org/downloads/
1.5 http://www.java.com/en/download/
1.6 http://www.java.com/en/ download/help/path.xml
1.7 https://www.nostarch.com/pythonwithminecraft/
1.8 https://minecraft.net/download
1.9 https://www.python.org/downloads/mac-osx/
1.10 http://www.oracle.com/technetwork/java/javase/downloads/index.html
1.11 https://www.nostarch.com/pythonwithminecraft/
1.12 http://www.raspberrypi.org/
10.1 https://www.nostarch.com/pythonwithminecraft/
11.1 http://pypi.python.org/
11.2 http://flask.pocoo.org/docs/0.10/tutorial/
12.1 https://www.nostarch.com/pythonwithminecraft/

Troublshooting

https://nostarch.com/minecrafthelp
The book Learn to Program with Minecraft requires Minecraft 1.8 or 1.9, Python 3.6 or newer and Java 8 or newer. If you're having difficulty getting your environment set up, software versions are the most likely problem. Follow the instructions on this page to check that you are using the correct versions of Minecraft, Python, and Java.

If you've confirmed that you have the correct versions and you're getting other errors, refer to the later sections in this document (linked below).

Pick the Right Minecraft Version
Am I Using the Right Version of Python?
Am I Using the Right Version of Java?
What If I Have Two Versions of Python on My Computer?
Start_Server, File Cannot Be Found (For Windows)
Connection Refused Error (For Mac)
Nothing Happens After I Click Install_API (For Windows)
Permissions Error When Installing API (For Mac)
Unicode Decode Error (For Windows)
I Got a Different Error!

Unfortunately, we do not have any dedicated Python programmers on our team, so we are unable to troubleshoot more complex errors. Sorry for the inconvenience!

Pick the Right Minecraft Version
Purchase the standard Minecraft version from minecraft.net to follow along with the book. You must have Java Edition for Windows and OSX or Pi Edition for the Raspberry Pi.

Please know that Minecraft Windows 10 Edition, Minecraft for Xbox, Minecraft: Education Edition, and Minecraft: Pocket Edition are not compatible with the book.

In order to use your Spigot server, your Minecraft version needs to match the Spigot version exactly. But new versions of Minecraft come out all the time, so if you update Minecraft, Spigot won’t work with the new version anymore. In order to make your Spigot and Minecraft versions match, you can set up a profile.

When you set up a profile, you tell Minecraft that you only want to use the version of the game that will work with the version of the server that you are using. In other words, a profile allows you to continue using the same server even when newer versions of Minecraft are released.

Once you set up a profile, you should be able to use our book’s coding directions and you'll know one more of Minecraft’s secrets, and will be further along on your journey to become a Minecraft Master!

Let’s get started.

For Windows

You’ll need to set up a profile to make sure Spigot and Minecraft are always running the same version. To start Spigot, follow these steps:

Step 1. Go to your Minecraft Python folder and open your Minecraft Tools folder.
Step 2. In the Minecraft Tools folder, double-click the Start_Server file. If you get a message asking whether you want to allow access, click Allow.
Step 3. A window will appear and begin to set up the server. If you see a message that says the server is out of date, don’t worry; you don’t need to update the server for it to work.
Step 4. Once the setup is finished, scroll to the top of the text in the window. Near the top (around the third or fourth line), you should see text saying Starting minecraft server version x.x.x. For example, 1.16.3.
Step 5. Make a note of the version number shown on your screen, and keep this window open.

Now that you know which server version you’re using, you can set up the game profile:

Step 1. Open the Minecraft launcher, but don’t click the green PLAY button quite yet (make sure you leave the server window open when you do this).
Step 2. At the top-right of the Minecraft launcher, click the menu button (which looks like three parallel lines), then click the Launch Options button. This will allow you to access the profile editor.
Step 3. Click the Add New button to create a new configuration.
Step 4. In the Name field, type Learn to Program with Minecraft.
Step 5. In the Version drop-down menu, select the version of the server that you’re using. For example, version 1.16.3.
Step 6. Click the Save button. Your profile has now been set up. Click the central Minecraft logo to return to the screen with the green PLAY button.

From now on, every time you want to use Minecraft with this book, click the arrow next to the Minecraft launcher’s start button. Select the Learn to Program with Minecraft option to use the correct version for the server. You can swap back to the latest version of Minecraft at any time by changing this drop-down menu to the Latest Release option. Once you have selected the correct version, click PLAY!

For Mac

You’ll need to set up a profile to make sure Spigot and Minecraft are always running the same version. To start Spigot, follow these steps:

Step 1. Go to your MinecraftPython folder and open your MinecraftTools folder.
Step 2. In the MinecraftTools folder, CONTROL-click the Start_Server file and select Open. (If you get an error message, go to System Preferences and then to Security and Privacy and click Open Anyway.)
Step 3. Once the setup is finished, scroll to the top of the text in the window. Near the top (around the third or fourth line), you should see text saying Starting minecraft server version x.x.x. For example, version 1.16.3.
Step 4. Make a note of the version number shown on your screen, and keep this window open.

Now that you know which server version you’re using, you can set up the game profile:

Step 1. Open the Minecraft launcher, but don’t click the green PLAY button quite yet.
Step 2. In the top-right corner of the Minecraft launcher, click the menu button (which looks like three parallel lines), then click the Launch Options button. This will allow you to access the profile editor. Click the Add New button to create a new configuration.
Step 3. In the Name field, type Learn to Program with Minecraft.
Step 4. In the Version drop-down menu, select the version of the server that you’re using. For example, version 1.16.3.
Step 5. Click the Save button. Your profile has now been set up. Click the X in the upper-right corner, then click the central Minecraft logo to return to the screen with the green PLAY button.

From now on, every time you want to use Minecraft with this book, select the Learn to Program with Minecraft option in the drop-down menu to the right of the green PLAY button. You can swap back to the latest version of Minecraft at any time by changing this drop-down menu to the Latest Release option.

Am I Using the Right Version of Python?
Follow these steps to make sure you're running Python 3.6 or newer.

Note: If you find that you have both Python 2 and Python 3 installed, you should uninstall Python 2—or follow the instructions in “What If I Have Two Versions of Python on My Computer?” below.

For Windows

The simplest way to confirm you’ve gotten the right version of Python is to go to the Start menu, then search for Python. If you don’t see a search box, you can just start typing Python to search. This will show you every version of Python that you have installed on your machine. The Python version number might be part of the name that shows up in the Start menu; if not, open IDLE and the version number will be displayed in the shell.

If you don’t have version 3.6 or newer, you’ll need to install the updated version. Follow the steps in “Installing Python” in the book.

For Mac

Step 1. Open Finder and search for Terminal. Click Terminal to open it.
Step 2. At the Terminal prompt, enter Python -V (note that the V is uppercase).
Step 3. You will see the Python version number—if it's anything older than 3.6, you'll need to install an updated version. Follow the steps in Chapter 1 to install Python version 3.6.

Am I Using the Right Version of Java?
Follow these steps to make sure you're running Java 8 or newer.

For Windows

You should be able to see all the installed programs in the Windows Start menu, including Java. The simplest way determine which version you have installed is to do the following:
Step 1. Go to the Start menu.
Step 2. Choose All Programs.
Step 3. Find the Java folder and click About Java.

You can also test the version of Java by using this method:
Step 1. Open the Start menu, search for cmd, and open the command prompt.
Step 2. Run the command java -version. You will see a message that says something like java version "1.8.0_72". The version of Java that you are using is the number after the first dot, which is version 8 in our example message. If your version is older than 8 (or if Java isn’t installed at all!), you’ll need to update or install Java. To do so, follow the installation instructions in Chapter 1.

For Mac

Step 1. Open Finder and search for Terminal. Click Terminal to open it.
Step 2. At the Terminal prompt, type java -version and press RETURN.
Step 3. You will see a message that says something like java version "1.8.0_72". The version of Java that you are using is the number after the first dot, in this case version 8. If your version is older than 8, you'll need to update Java. To do so, follow the installation instructions in Chapter 1.

What If I Have Two Versions of Python on My Computer?
If you want to have both Python 3 and an older version of Python installed, and if you have an older version of the Install_API file, you need to modify the file to specify that it should use Python 3 rather than the older version.

The Minecraft Python API will work with older versions of Python, but you must use Python 3 if you want to run all the code examples from this book—otherwise you’ll get an error if you try to use the print() function and a few other Python things. But you can still keep another, older version of Python on your computer if you want to.

Install the Minecraft Python API by following the Windows or Mac instructions in the following sections. Once you’ve installed the API, you’ll need to make sure that you use the correct version of IDLE. Make sure you use IDLE 3 when writing and running code—otherwise the programs from this book will not work.

For Windows

If you have the older version of the Install_API file, then you’ll need to modify it. To modify the In-stall_API file, follow these steps:

Step 1. Open the Minecraft Tools folder and find the Install_API file.
Step 2. Right-click the Install_API file and select Edit.
Step 3. Once the file opens, find the line that begins with this:

python -m pip install minecraftPythonAPI.zip

Step 4. Edit the line by changing python to python3 so that the line looks like this:

py -3 -m pip install minecraftPythonAPI.zip

Step 5. Save the file and close it.
Step 6. Double-click the Install_API file to install the Minecraft Python API.

For Mac

If you have the older version of the Install_API file, then you’ll need to modify it. To modify the In-stall_API file, follow these steps:

Step 1. Open the Minecraft Tools folder and find the Install_API file.
Step 2. Control-click the Install_API file and select Edit.
Step 3. Once the file opens, find the line that begins with this:

python -m pip install minecraftPythonAPI.zip

Step 4. If you can’t find that line, then you already have the new file and don’t need to do anything else. Otherwise, edit the line by changing python to python3 so that the line looks like this:
python3 -m pip install minecraftPythonAPI.zip

Step 5. Save the file and close it.
Step 6. Double-click the Install_API file to install the Minecraft Python API.

Start_Server, File Cannot Be Found (For Windows)
When you click on the Start_Server file you might see a window saying “Windows cannot find 'C:\Users\Frank\Documents'” or something similar.

To work around this issue, open the server folder and double click on the start.bat file. The server should start normally. Every time you need to start the server in the future repeat these steps.

Alternatively, download the latest version of the book's setup files, Minecraft Tools, linked on the book's web page.

Connection Refused Error (For Mac)
In Python, after typing the line mc = Minecraft.create(), you might get an error message like this:

ConnectionRefusedError: [Errno 61] Connection refused

or a similar error like this:

ConnectionRefusedError: [Errno 10061] No connection could be made because the target machine actively refused it.

This error is most frequently caused by an out-of-date version of Java installed on your computer. In order to fix this issue, follow the Java installation instructions in Chapter 1.

If you still get this error after reinstalling Java, your Mac might be using an old version of Java only on the command line. To fix this issue, do the following:

Step 1. Click the search icon on the top-right corner of your screen.
Step 2. In the search box, enter Java Preferences.
Step 3. When the preferences box opens, make sure that only the Java 8 checkbox is ticked.

After you have changed these preferences, the problem should be resolved. However, if you still have this issue, uninstall older versions of Java and then reinstall Java 8.

Nothing Happens After I Click on Install_API (For Windows)
When you run the Install_API file during step 5 of “Installing the Minecraft Python API and Spigot” (page 6), you might see a black window pop up.

If you see a window like this, you might be experiencing a bug with pip, which is used to install the API. To work around this, you need to install the Minecraft Python API via the command line. Follow these steps:

Step 1. Open the Minecraft Tools folder. You should see the minecraftPythonAPI.zip file.
Step 2. In the file browser, click the address bar to highlight it, then copy the text (right-click and select Copy, or press CTRL-C). The address should look something like this:

C:\Users\user\Minecraft Python\Minecraft Tools

Step 3. Click the Start menu and search for PowerShell. Click PowerShell to open it.
Step 4. At the PowerShell prompt, type cd and then right-click to paste the address of your Minecraft Tools folder.
Step 5. Add single quotation marks around the text you just pasted. The line should look something like this:

cd 'C:\Users\user\Minecraft Python\Minecraft Tools'

Step 6. Press ENTER. Now you can run commands in PowerShell using the contents of the Minecraft Tools folder.
Step 7. On the next line, type the following command to install the API:

python -m pip install minecraftPythonAPI.zip

Step 8. Press ENTER. The Python API should now be installed correctly.

Permissions Error When Installing API (For Mac)
During step 8 of “Installing the Minecraft Python API and Spigot” in Chapter 1, you might get this error:

The directory '/Users/YourUserName/Library/Caches/pip/http' or its parent
directory is not owned by the current user and the cache has been
disabled. Please check the permissions and owner of that directory. If
executing pip with sudo, you may want sudo's -H flag.

Check all the folders that the Install_API file is inside of and remove any spaces from the folder names. To do this, follow these steps:

Step 1. Control-click the icon of the folder with a space in the name.
Step 2. From the pop-up menu, select Rename, then remove the space from the folder’s name. Note that you should not have to do this with the hard drive itself (Macintosh HD)!

Once you have done this, try running the Install_API file again.
On some Macs, you might still get an error—however, the API has still installed correctly. If you see the following line, the API has installed correctly and you can ignore the error message:

Requirement already satisfied (use -–upgrade to upgrade): py3minepi…

Unicode Decode Error (For Windows)
When you run the Install_API file during step 5 of “Installing the Minecraft Python API and Spigot” in Chapter 1, you might get this error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 44: invalid start byte

Your Windows system may be using an encoding method that's different from the one Python assumes. Follow these steps:

Step 1. Navigate to

'C:\Users\user\AppData\Local\Programs\Python\Python36\Lib\site-packages\pip\compat'

This path is for those running Python 3.6 and will differ slightly for other versions.

Step 2. Open init.py in a text editor, and change line 75 to this:

return s.decode('cp949')

Making this change and saving the file should resolve the problem.

I Got a Different Error!
Unfortunately, we do not have a dedicated Python programmer on our team, so we are unable to troubleshoot more complicated issues on your behalf at this time. If you get an error that isn't listed on this page, we would encourage you to search for the error online. We're sorry for the inconvenience, but thank you for your understanding!

查找wordpress数据库密码

查找mariadb数据库密码

查找wp-config.php这个文件,找到password就可以

# find -name wp-config.php
./var/www/html/wordpress/wp-config.php
# vi ./var/www/html/wordpress/wp-config.php

while用法

When condition is true, which include the result(true or false) of operator like 'not equal(!=)' or 'less than(<)'or 'greater than or equal to(>=)', the statement after colon will be executed.

When we use function input, the function will return string type, so if we want compare result with number, we can use str() to convert number to string and int() to convert string to int.

message = input('if you input 0,then everthing is over')
i = 1
while message != str(0) and i <=10 :
    print(str(i)+' '+message)
    i +=1

cv2.destroyAllWindows()出错

Jupyter's error can not be solved immediately, however when I run the script in terminal, error message is here:

.../Study/learningOC[15:52]python3 cameraFrames.py
Showing camera feed. Click window or press any key to stop.
Traceback (most recent call last):
  File "...Study/learningOC/cameraFrames.py", line 19, in <module>
    cv2.destroyAllWindows('MyWindow')
SystemError: <built-in function destroyAllWindows> returned NULL without setting an error

Therefore I check the demo code:

import cv2

clicked = False
def onMouse(event, x, y, flags, param):
    global clicked
    if event == cv2.EVENT_LBUTTONUP:
        clicked = True

cameraCapture = cv2.VideoCapture(0)
cv2.namedWindow('MyWindow')
cv2.setMouseCallback('MyWindow', onMouse)

print('Showing camera feed. Click window or press any key to stop.')
success, frame = cameraCapture.read()
while success and cv2.waitKey(1) == -1 and not clicked:
    cv2.imshow('MyWindow',frame)
    success, frame = cameraCapture.read()

#cv2.destroyAllWindows('MyWindow')
cv2.destroyAllWindows()
cameraCapture.release()

After deleting the arguments 'MyWidows' in destroyAllWindows, the script is running well.

解决opt_flow.py问题

terminal问题

昨天测试opt_flow还正常,今天发现在studio code下面就现实无法获取摄像头权限(hist.py都正常),命令行模式也无法运行。
做了如下修改:

brew update-reset

同时修改了pip的源(从清华修改为科大)。
因为做了两个操作,我也不清楚是哪个起了作用,命令行模式是ok了。

vscode问题

国外大拿分析(见参考),vscode下opcv摄像头没有权限,是由于apple mac没有给予vscode权限,在system preference里的camera部分,也没有能够增加vscode的地方,因此需要直接修改security&privacy存储数据的地方,见下面。完成后重启vscode即可(修改前,需要在system preference里授予terminal-Full Disk Access权限)

cd ~/Library/Application Support/com.apple.TCC
cp TCC.db TCC.db_backup
sqlite3 TCC.db
INSERT into access (service, client, client_type, auth_value, auth_reason, auth_version) VALUES ("kTCCServiceCamera","com.microsoft.VSCode",0,2,0,1);
INSERT into access (service, client, client_type, auth_value, auth_reason, auth_version) VALUES ("kTCCServiceMicrophone","com.microsoft.VSCode",0,2,0,1);
.exit

Screen Shot 2021-02-22 at 21.55.12

参考
vscode获得camera权限

pip3使用国内源更新&解决futu-api库安装问题

方法1

使用如下命令。

python3 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip

但是在安装futu-api时,总是报错,如下
Screen Shot 2021-02-21 at 18.52.38

分析核心问题应该是

WARNING: You are using pip version 20.2.3; however, version 21.0.1 is available.
You should consider upgrading via the '/usr/local/opt/python@3.9/bin/python3.9 -m pip install --upgrade pip' command.

采用方法1的时候,很有可能并没有更新pip3,还是在错误的目录下下载文件。
所以需要首先确定pip3的版本最新,那么只有进行全局变量的配置,见方法2

方法2

mac和linux配置方法相同

mkdir ~/.pip
vi ~/.pip/pip.conf

在文件中粘贴如下内容,用科大源替换也可以。

[global]
 
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
 
trusted-host = pypi.tuna.tsinghua.edu.cn

然后升级

sudo pip3 install --upgrade pip

Screen Shot 2021-02-21 at 19.01.32

参考
替换pip国内源
替换pip国内源/tencent

国内的pip源

阿里云:https://mirrors.aliyun.com/pypi/simple/
清华:https://pypi.tuna.tsinghua.edu.cn/simple
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/

解决No module name ‘futu’问题

运行futu给的demo代码,总是出现如下错误,找不到futu api这个库
Screen Shot 2021-02-21 at 22.35.10
但是采用python2调用时,则没有类似告警。
这基本可以判断,问题是mac上有两套python环境导致的(mac自带python2环境)。
解决方法如下

  1. 在python3下运行如下代码,获得python3的interpreter路径

    >>> import sys
    >>> print(sys.executable)
    /usr/local/opt/python@3.9/bin/python3.9
  2. 在命令行下(注意,不是python环境下),进入interpreter路径执行安装futu-api命令
    不过这里我也没有搞懂,为什么不适用pip3也能安装成功

    ➜ /usr/local/opt/python@3.9/bin/python3.9 -m pip install futu-api
    

    下面则是执行demo代码成功的结果。
    Screen Shot 2021-02-21 at 22.45.57

参考
富途Q&A

解决opencv演示sample问题/安装python3缺少的numpy库

在macbook pro上,无法正常演示opencv自带的sample文件,显示没有numpy库。

发现如果使用python2是正常的,而是python3(也包括visual studio code)缺少对应的库,解决问题方法如下。

查看目前库

首先通过list命令,对比pip和pip3,即python2(mac自带)和python3相关库的情况,结果是python的非常少

pip list
pip3 list 

也可以用freeze命令。

pip3 freeze

安装numpy库

正常采用如下命令

pip3 install numpy

但是国外的源太慢,更换成科大的,速度飞起

pip3 install --index-url https://pypi.mirrors.ustc.edu.cn/simple/ numpy

下图是通过科大源安装matplotlib的情况,速度快如闪电。
Screen Shot 2021-02-17 at 11.03.13 PM

如下是国内源列表

    清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/

    阿里云 http://mirrors.aliyun.com/pypi/simple/

    中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

    豆瓣(douban) http://pypi.douban.com/simple/

参考如下
国内源
pip vs pip3
numpy tutorial 1/official
numpy tutorials 2

验证numpy是否安装的小技巧

numpy

如下

>>> from numpy import *
>>> eye(4)
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])

Brew

mac更新到big sur之后,brew运行就不正常。在发现使用更新中科大源之前,我才用的是如下方法,也能解决问题,只不过在imac上可以正常安装opencv,而mac pro上则失败了,后来在两台电脑上全部重新安装了中科大版本的brew,才最终解决,下面将原操作做个记录。

  • 首先,在使用brew list或brew doctor后,出现的是下面的问题

    Traceback (most recent call last):
    11: from /usr/local/Homebrew/Library/Homebrew/brew.rb:23:in `<main>'
    10: from /usr/local/Homebrew/Library/Homebrew/brew.rb:23:in `require_relative'
    9: from /usr/local/Homebrew/Library/Homebrew/global.rb:37:in `<top (required)>'
    8: from /usr/local/Homebrew/Library/Homebrew/vendor/portable-ruby/2.6.3/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    7: from /usr/local/Homebrew/Library/Homebrew/vendor/portable-ruby/2.6.3/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    6: from /usr/local/Homebrew/Library/Homebrew/os.rb:3:in `<top (required)>'
  • 然后,删除xcode工具,并重新安装

    sudo rm -rf /Library/Developer/CommandLineTools
    sudo xcode-select --install
    
  • 最后,更新brew即可

    brew upgrade
    

    当然,最好的方法是

    brew update-reset
    brew cleanup
    

    参考
    brew更新问题
    更换科大brew源

brew和zsh的小问题

brew

昨天开始学习opencv,一天时间把环境都没有搞好,主要是mac系统升级到big sur以后,brew出现了很多告警,而且跟新起来除了很多问题,包括使用【brew update-reset】重新安装xcode tools也不行,终于下定决心,重新安装brew,问题基本搞定,安装脚本如下

/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"

然后依次安装opencv和scipy库

brew doctor
brew install python(我已经安装好了)
brew install opencv
brew install scipy

查看opencv版本如下

opencv_version

ZSH

使用国内中科大的源,安装完brew后,每次打开terminal,会出现如下提示

[oh-my-zsh] Insecure completion-dependent directories detected:
drwxrwxrwx 7 hans admin 238 2 9 10:13 /usr/local/share/zsh
drwxrwxrwx 6 hans admin 204 10 1 2017 /usr/local/share/zsh/site-functions

大意是zsh认为目录权限有问题,解决方法如下

chmod 755 /usr/local/share/zsh
chmod 755 /usr/local/share/zsh/site-functions

参考
1 zsh问题
2 brew中科大源