个人资料
归档
正文

python

(2020-01-03 19:14:58) 下一个

https://stackoverflow.com/questions/29123840/how-to-generate-test-report-using-pytest

1. Python须知

通常认为是脚本。虽是目前数一数二的软件,插件和包很多,也许是比较简单,据说是解释和编译都行。缺点有版本不兼容和更新快,但是最讨厌的是:

1.1 缩进的句法:

上面这段程序,倒数第2行若无4个空格,则最后一行被排除在for loop外,解释器会报错。换句话说,空行必须包含适当的空格以保持上下文的连续性。增加代码后一定要查缩进。

在pycharm下,你特意的留空在保存文件后消失。需要点击Settings|CodeStyle|Python|Tabs and Indents下的Keepindents on empty line。而且这个语言的下拉单不是每次都显,点几次Code Style前的下拉箭头你就知道了。

1.2 不统一的安装路径

特别是Windows下,全局装在Program Files下,单用户在C:AppDataRoamingPython下,在AppData下就可以有几个安装目录,还有是否用了虚拟环境,Linux下有类似问题。此时,相关的包不知连到哪个解释器下,相关软件可能只寻找局部或全局的包,可能得装多次。这种机制有个好处就是可以装不同版本的Python。全局安装的问题是如果你在程序中安装包与有授权的问题,在控制台下安装可以右击以admin权限运行控制台。在装包时建议指定相关的Python.exe路径(蓝色字串),不然未必知道安装是与哪个解释器绑定的:"c:Program FilesPython38python.exe" -m pip install auto-py-to-exe

如果Ubuntu下pip有问题:https://stackoverflow.com/questions/69503329/pip-is-not-working-for-python-3-10-on-ubuntu/69527217#69527217? 

用PyCharm时若不用已装的解释器而新建env,则每个项目都会拷贝一套解释器和site package。创建新项目时,Location的选择可以是现有目录,解释器建议选Previously configured interpreter|Add Local Interpreter,如下: 

1.3 版本不兼容

网上许多例子都是v2的,特点之一是print内容没括号。

1.4 调用/import

import用于各种包/库的引用。任何外部文件如ex.py可以被import py或from py import subd引用。但是,import某文件可能导致它被执行,即便是def函数也会被执行。要想它们只在被调用时执行,可以把它们都放在class里,而主程序用下述语句:

def main():
    print('main')

if __name__ == "__main__":
    main()  #被import 时将不运行main()

2. Install

安装时注意选上路径,这样无论在哪个目录下,py都可运行python。不要用缺省安装,选all users以便装到Programs下面。原带IDLE功能一般,可在notepad++下定义热键Alt+P来运行当前编辑窗口中的python程序,方法是:选Run|Run,键入py "$(FULL_CURRENT_PATH)",点击Save并选择热键。

python
>>>import os
>>>os.system('cd')                 
>>>^z
notepad hello.py
print("Hello Python world!")   #save and quit, then run the script:
python hello.py

2.1 pip安装工具:C:UsersYingzhouDaiAppDataLocalProgramsPythonPython310>python get-pip.py
  WARNING: The scripts pip.exe, pip3.10.exe and pip3.exe are installed in 'C:UsersYingzhouDaiAppDataLocalProgramsPythonPython310Scripts' which is not in PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-22.1.1 wheel-0.37.1

2.2 Poetry安装管理工具:

比pip好的是它也管理卸载:python.exe -m pip install poetry
[PS]> poetry shell 
[PS]> Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass 

2.3 路径和包https://www.shivmanlabs.com/post/how-to-add-python-path-to-environmental-variables  常见为 C:UsersnameAppDataRoamingPython  C:UsersnameAppDataLocalProgramsPython 及其下Scripts。如果有多个python版本,建议安装包命令:path_to_my_python.exe -m pip install PACKAGE_NAME_HERE 如果安装包含后import报错,可以增加PYTHONPATH,用下列命令查看:
>>>import sys
>>>sys.path

pip install psutil //computer util
pip install requests //http
pip install python-forecastio
https://pyvisa.readthedocs.io/en/latest/introduction/getting.html NI/Keysight GPIB/232/Eth ctrl
pip list
py --version
>>> import tkinter
>>> tkinter.TkVersion

v3.10.2 @Jan.2022   https://freepdf-books.com/ 

Pycharm常找不到包而在cmd下运行python又没问题。关键是File|New project setup要定义解释器并查看包,而不是右击Modify run config下。

Parcharm找不到包是配置问题。vscode好些,装个微软的python pluging就行,颜色更丰富。推荐。

2.4 其它包

2.4.1 py转exe

(psgdemos里有):  https://pysimplegui.readthedocs.io/en/latest/cookbook/ 

Python 生成 Windows 執行檔教學 我已經用過pyinstaller很多次但還是常採坑.
最新的我用虛擬環境,但沒注意到有個library是裝在外面,pyinstaller沒辦法打包不在虛擬環境內安裝的library.裝在虛擬環境裡面就好了

pyInstaller -F hello.py 针对单文件;pyInstaller -D mycode.py则针对目录, 生成的exe在dist|下。后者我包括了3个源文件,GUI调用可独立运行的console和包检查安装程序,在W10下没有问题。--add-data 和--add-binary 分别添加文本和二进制文件,例如--add-binary="pyidmffmpeg.exe;."或--add-binary="libfoo.so:lib"。我没用它们,也可直接拷贝到目标目录下。转好后运行dist/mycode/mycode.exe,如果缺少如setuptools模块用后python.exe -m pip install --upgrade setuptools安装。我实际的命令:pyinstaller --add-binary="pyidmffmpeg.exe;."  -D pyidm.py

不推荐某人做的GUI即auto_py_to_exe,它不过是调用pyInstaller而且很垃圾:https://github.com/brentvollebregt/auto-py-to-exe/issues/309 

我另一项目包括GUI和console app,两者可独立运行,GUI调用console.py,因此我用pyInstaller -F 分别生成了两个可执行文件。

科学工具:pip install Scipy pip install numpy
GUI: pip install PySimpleGUI    https://pysimplegui.readthedocs.io/en/latest/cookbook/#the-pysimplegui-cookbook 
GUI百例:C:UsersYingzhouDai>psgdemos
python -m pip install -U matplotlib ;
https://matplotlib.org/stable/users/installing/index.html 
Excel图形:pip install matplotlib pip install pillow https://edadocs.software.keysight.com/kkbopen/how-does-sin-x-x-sinc-interpolation-work-616372293.html 

Excel包https://pypi.org/project/openpyxl/    https://openpyxl.readthedocs.io/en/stable/  https://realpython.com/openpyxl-excel-spreadsheets-python/ https://www.geeksforgeeks.org/python-reading-excel-file-using-openpyxl-module/
C:UsersYingzhouDaiAppDataLocalProgramsPythonPython310Scripts>pip install openpyxl

Anaconda
https://blog.csdn.net/ITLearnHall/article/details/81708148 装完后,搜索anaconda并运行;直接打开cmd运行conda是不行的。
 
 requriements.txt 和setuptools
pip install -r requirements.txt
如果是多平台,你会用到setup.py/setup.cfg。
2.4 requirements
1)首先产生requirements.txt:
pip freeze > requirements.txt
这个产生全局的模块列表,要只产生某个项目的且包含子模块,用:
pip install pipreqs && pip install pip-tools
pipreqs --savepath=requirements.in && pip-compile
2)安装
pip install -r requirements.txt

3.学习和实例

3.1 在线教程https://www.w3schools.com/python/python_ml_getting_started.asp?  https://www.tutorialspoint.com/python/index.htm  其中print的内容在v3.8下运行都要加括号。https://www.pythontutorial.net/python-basics/ https://docs.python.org/3/howto/regex.html https://realpython.com/python-sockets/ regular expression不直观,看实例:https://www.w3schools.com/python/python_regex.asp

https://docs.python.org/3/tutorial  https://github.com/EvanLi  https://www.jb51.net/article/233156.htm 

Python编程:从入门到实践(Python Crush Course) -code:https://nostarch.com/pythoncrashcourse2e; 流畅的Python(fluent python) 更多书籍:http://www.lanjuhua.com/s/WiQBL1V_BzkBNVdp/id/6894715807

3.2 Access Internet - result 200

import urllib.request
weburl = urllib.request.urlopen('https://www.youtube.com/user/guru99com')
print("result: " + str(weburl.getcode()))

3.3 Show time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

3.4 Send email

import smtplib
msg = email.message_from_string('context')
msg['From'] = "yzdai@hotmail.com"
msg['To'] = "yzdai@yahoo.com"
msg['Subject'] = "TestPythonTitle"
s = smtplib.SMTP("smtp.live.com",587)
s.ehlo() # Hostname to send for this command defaults to the fully qualified domain name of the local host.
s.starttls() #Puts connection to SMTP server in TLS mode
s.ehlo()
s.login('yzdai@hotmail.com', 'yourpasswd')
s.sendmail("yzdai@hotmail.com", "yzdai@yahoo.com", msg.as_string())
s.quit()

3.5 Multithread

3.5.1 

import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

background.join()    # Wait for the background task to finish
print('Main program waited until background was done.')

3.2 threading

# Python program to illustrate the concept of

# threading importing the threading module
import threading
def print_cube(num):
    """
    function to print cube of given num
    """
    print("Cube: {}".format(num * num * num))
def print_square(num):
    """
    function to print square of given num
    """
    print("Square: {}".format(num * num))
if __name__ == "__main__":
    # creating thread
    t1 = threading.Thread(target=print_square, args=(10,))
    t2 = threading.Thread(target=print_cube, args=(10,))
    # starting thread 1
    t1.start()
    # starting thread 2
    t2.start()
    # wait until thread 1 is completely executed
    t1.join()
    # wait until thread 2 is completely executed
    t2.join()
    # both threads completely executed
    print("Done!")
3.3 更好的实例
s是串口的list,程序用thread打开每个串口,调check_serial_port读写每个串口,根据响应判断出终端类型,返回结果dict={'BMC':'COM5'}一类。
在所有终端都找到后,event.set()给各任务发消息使其退出。
import concurrent.futures

 
3.6 OS
import os
os.getcwd()      # Return the current working directory, or use:
os.system('cd')
os.chdir('/server/accesslogs')   # Change current working directory
os.system('mkdir today')   # Run the command mkdir in the system shell
dir(os)
help(os)
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')
import glob
glob.glob('*.py')
import sys
print(sys.argv)

3.7 file I/O

import os
print(os.getcwd())
f = open("pydemo.txt", "w")
f.write("File write or reaplce mode, not append mode!")
f.close()
f = open("pydemo.txt", "r")
s = f.read(10);
s1 = f.read();
print(s,s1)
f.close()
import os.path
file_exists = os.path.exists('pydemo2.txt')
if file_exists:
  os.remove("pydemo2.txt")
  
os.rename( "pydemo.txt", "pydemo2.txt" )
f = open("pydemo2.txt", "r")
s = f.read(10);
position = f.seek(0, 0);
s1 = f.read();
print(s, s1)
f.close()

4. GUI & IDE

4.1 Basic tool

https://realpython.com/python-gui-tkinter/  https://pythonguides.com/python-tkinter-listbox/

#pip install tk
import tkinter as tk
top = tk.Tk()
# Code to add widgets will go here...
top.mainloop()    #1st window
window = tk.Tk()  #2nd window
greeting = tk.Label(text="Hello, Tkinter")
greeting.pack()

4.2 PyCharm IDE

pySimpleGUI是目前比较火的开源包,能实现非常复杂的GUI。官方支持的IDE有两个,vs code和pycharm,前者免费但开销大更新快比较罗嗦,后者价格不菲按年收费但community或教育版免费,比专业版少了一些功能。中文指南:PyCharm 中文指南(Win版) 2.0 iswbm王炳明(github.com)

安装后用Alt+Sht+S配置python 3.8解释器,然后点击+号安装模块例如pycurl。自此可以运行pyidm.py下载youtube视频。

VersionControl见3.2.1,Debug有单步/断电/回到现场等功能,Terminal是Windows PowerShell,Packages是包管理器,Console是并行工作的解释器,对现场调试正则表达式特别方便。热键(注意Lenovo下Fx需按Fn+Fx):https://resources.jetbrains.com/storage/products/pycharm/docs/PyCharm_ReferenceCard.pdf 

^P/^Q可以显示函数原型/函数注释(DocString),显示函数源码有两种方法:Ctrl+Sht+I跳转到函数,Ctrl+Sht+i则弹出窗口显示。

Ctrl F/R:find/replace

F2/ShtF2:跳转到下/上个错误

Alt ^/Alt v:  跳转到上/下个def

Alt 6:增加TODO/注释,即程序员的思路或待编程码

Alt v:最近的收索记录

起步:File|New Project, File|New Scratch。运行参数需右击程序名tab,选More Run/Debug->Modify Run Configuration...,但更快的是点击icon行右侧运行按钮前,程序名向下按钮。

选中一段程序按Alt+Sht+E可以运行它,或右击选Execute Slelection

要debug,点击某行左侧使显示红圆点,在点击爬虫即debug图标,程序将停在断点处并显示单步等图标在下部窗口上端。

屏幕最底行是状态,上一行的常用tab是版本控制、TODO、问题、包、Python console、Terminal。在调试时,下部左可选择相关函数,中部是变量可点击修改,右边是变量窗口。调试时变量值会显示在源码行或鼠标位置;变量窗可加入监视变量,点击右端的...可扩展list/dic的值。

Getting Started with PyCharm 7/8: Testing 系列教程的测试篇,右击函数名选Go to|Test会生成测试程序框架,可方便的import该函数并给予实参,运行后会显示测试覆盖率。 

4.2.1 console paramter

右击选Run configuration,所填参数要双引号括起,目录是单个反折线,interprete options是-s?注意只在第二行选中文件名而非Current File时有效。

4.2.2 Git版本控制

右击文件名选Local History可方便的与本地或clone出的版本比较,无需VCS。

VCS|Get from version control, Download and install Git,填入github源码URL;

点击VCS|Enable并选Git,该VCS和左下Versiona Control都会变成Git;

登录Gitlab或Github,点+号创建一个项目,在clone出选择相关URL如https;

在Pycharm中选Git|Clone,键入上面拷贝的URL,登录名和口令,选打开为新窗口。用File|New创建,或Open选已有的项目目录。

在左侧窗口高亮所有要推送到Gitlab的文件,右击选Git及其最上面的Add,将这些文件加入VCS;

点击最左边Project下的Commit纽,这两个纽都是纵向tab,选中要上载的文件并填写备注文本,如此次提交的是啥,改正的错误描述;然后点击Commit或Commit and Push纽,如果只点了Commit可以另外用右上方的Git push。Push就是上推到网上,在Gitlab或刷新后的GitHub上可以看见其内容。

Gitlab/Github的配置和使用:https://cloud.tencent.com/developer/article/1478265?输入 GitHub 仓库的地址和本地目录时,目录必须是空的,PyCharm 新建项目的时候,会自动创建 .idea 文件夹,这个必须删掉。 在项目中新建文件,弹出提示框:是否将文件添加到 Git。勾上 Remember, don't ask again 再点击【Yes】。点击左侧垂直tab,选要commit的文件并输入Commit Message后点击下方【Commit】。已经提交的文件文件名显示是 白色,未提交的文件文件名显示是 绿色。最后选右上方Push.

如果是先有本地目录,VCS|Get from version control, Download and install Git,填入github源码URL; 这一步要改成VCS|Manager remote,填入github源码URL。第一次commit/push后,在gitlab中要做merge request才能完成。

使用远端时可能会有超时错误,重试就会弹出“Use your browser to login in”,登录Git后才会正常操作。

 https://www.youtube.com/watch?v=zrsqqyN2me8 https://www.youtube.com/watch?v=-_g3QITLaQA https://blog.csdn.net/zd147896325/article/details/89540477 

PyCharm In-Depth VCS #1: Getting Started https://www.youtube.com/watch?v=_w9XWHDSSa4 https://www.youtube.com/watch?v=AHkiCKG-JhM 详见另文。

Git and GitHub Tutorials: https://www.youtube.com/watch?v=r50BKIFGCI0?  https://www.youtube.com/watch?v=hMfi_ONvGEs https://www.youtube.com/watch?v=iJKIxrJ40ss 

Gitlab Tutorial: GitLab Beginner Tutorial 1 | Introduction and Getting Started - YouTube 

4.2.3 代码整形

Code|Reformat code。注意2020.2开始没有tab的定义了,强制为4个空格,但Ctrl+Alt+S可选择按原文件的缩进。这个只是辅助,例如def后的程序行,还是得人工开始缩进;不过一旦for缩进了,余下的行可以整形。参见0.1节。

2022版无效?安装sudo pip install autopep8,再选Tools|ExternalTools加autopep8,再选中一段代码,右击选ExternalTools->autopep8,即可按Pep8标准整形代码。

JSON字串整形:Ctrl+Alt+L,或安装JSON Parser插件,其在右侧显示。

4.2.4 插件与工具

点击左侧Plugins可以安装Regex Tester,用于测试正则表达式。安装后点击左下角的双叠方框,在窗口中输入例如:^1(3|4|5|7|8)d{9},匹配的字符串会显示高亮。

点击Tools的Add new bash console,可以弹出 Bash 窗口,使用 Linux 命令如ls -l

选中代码段后,右击并选Execute Selection in Python Console或热键Alt+Sht-Et-E,可弹出Python shell并执行该段代码。

误删恢复:在项目目录里点击右键,选 Local History 再选Show History,在删除的记录项上右击选择 Revert 。

块编辑:乒乓开关是Alt+Sht+Insert,或右击后选Column select mode。

改变量/函数名:Sht+F6/Ctrl+F6

File|Settings|Project|Interpreter,可显示/管理已装的包。

隐藏/重显左侧项目树:点击左侧垂直显示的Project。

文件只读/可写:点击右下角的锁图标置为只读,编辑时会弹出窗口允许解锁。

自动加载包:在函数名上按Alt+Enter,在弹出图标上选择包将自动 import - not work

显示项目数中包函数源码:在包/函数名上右击,Open in选Explorer或Terminal

4.3 Spyder

Anaconda自带。在W11可用PIP安装,Win10/MAC下载安装包,Ubuntu 20.04下用APT装但是版本旧。比PyCharm简单,pkg功能差些,没有版本控制如Git接口,但是免费,有variable explorer可以观看修改当前运行脚本的全部变量。数组变量可以双击后修改各分量。其它脚本调用VariableExplorer中变量,通常需在Run|General settings勾上Run in console's name space。与Pycharm相比,后者右下部是debug相关的变量,点击右端可弹出数组分量,在源码行的右端,或光标停在某变量上都会显示其值。

run/debug有10个图标:运行符号>、单元运行》(cell是以#%%或分开的行)、选择块运行I>(类似选中一段代码以Ctrl+Enter执行),Step in/out等。

左窗是源码,右上窗下部tab有Help|VariableExporer|Plot|Files,右下的tab有IPython Console和History。两者顶部都有选择项,如右上的object前可以选择Source是Editor或Console,选后者并键入如numpy.array可显示函数定义。右上选Plot时,上部有Save/Copy、放缩等纽,右上三横图标有相关功能。

Ctrl+I显示函数定义;要不受限制的显示图形,点击扳手图标(Preference)|IPython console|Graphics,Backend里由Inline改填Qt5,再重开Spyder。新法是View|Lock Panes and Tool bars的选择与否。三窗的右上角三横图标里也有窗口Lock与否的选择,还可水平/垂直分屏,或选择New以创建新窗打开新文件。

不支持PySimpleGUI。

http://docs.spyder-ide.org/5/  https://blog.csdn.net/qq_33793599/article/details/81359947 

4.4 IPython

https://blog.csdn.net/qq_27825451/article/details/84320859 交互式Python shell,带输入输出行号及颜色,按Tab显示相关变量/函数,变量后加?显示定义(加??显示源码,还可用re.*find*模糊查找),用hist [n]显示历史记录,%run 运行程序,!运行shell命令,等。Pycharm/Spyder均内置IPython,在调试时均为现场相关,可观看修改变量和运行程序。

4.5 不同平台

    from sys import platform
    if platform == "linux" or platform == "linux2":
        if cmd == "notepad++":
            cmd = "/snap/bin/notepad-plus-plus"
        elif cmd == "bluegriffon":
            cmd = "/usr/bin/bluegriffon"
    elif platform == "darwin":  # OS X
        print("cmdexec err-1000: OS platform not supported.")
        return 1000
    elif platform == "win32":  # win32/64
        if cmd == "notepad++":
            cmd = "c:Program FilesNotepad++notepad++.exe"
            # c:ProgramDataMicrosoftWindowsStart MenuProgramsNotepad++.lnk
        elif cmd == "bluegriffon":
            cmd = "C:ProgramDataMicrosoftWindowsStart MenuProgramsBlueGriffonBlueGriffon.lnk"

libreoffice --calc 

4.6 PyIDM & PyCurl

PyIDM是网上视频下载器,2020.5停止开发并去除支持及win版下载,可下载的源码有些旧风格的编码,在Ubuntu 20.04下安装正常运行崩溃与gtk有关,windows下有LibCurl但PyCurl不能利用安装出错,有的是须在MingW32环境下编译,或者报缺少头文件,或者关于需要的包名称不清,相关说明也挺乱的。我花了一天半让PyIDM在Win下运行但还是没有PyCurl。以下备忘。

git clone https://github.com/pycurl/pycurl.git  这里https://curl.se/download.html下载Curl的Win/Linux源码,注意win10/11有带,Curl-V可见版本如7.83.1(20220513)。按此处 http://pycurl.io/docs/latest/install.html Win下配置Pycurl的命令是:

python setup.py --curl-dir=c:dev|curl-7.33.0|builds|libcurl-vc-x86-release-dll-ipv6-sspi-spnego-winssl --use-libcurl-dll

这里目录指向libcurl头文件和DLL库。官方是运行winbuild.py,我的出错-也许只能在MingW32下运行。上述命令中的buidls和dll在我下载的curl里根本没有。官版说明未给实际编译的方法,开源码的混乱可见一斑。https://truxton2blog.com/pycurl-performance-differs/? 

后来找到这个今年的帖子:

https://knowledge.informatica.com/s/article/HOW-TO-Build-Libcurl-Libraries-for-Windows-and-Linux-for-Data-Archive?language=en_US 需要Visual studio 2019:https://docs.microsoft.com/en-us/visualstudio/releases/2019/history#installing-an-earlier-release 

又找到这个,原来最后一个windows版是https://pypi.org/project/pycurl/7.43.0.5/#files 如果你只是运行pip install pycurl==7.43.0.5 它照样以为你在Linux下。因此我下载了其windows版-2020.1.29,又在此处下载比它稍旧的https://www.python.org/downloads/release/python-381/ 但是3.10.4也可以用它。

其实到这里,我脑子里只剩下一个字:操!
脑子里又跑出一个小人,说:You got what you pay for! PyCurl is free!

"c:Program Filespython38python.exe"
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pycurl
>>>

https://www.lfd.uci.edu/~gohlke/pythonlibs/#pycurl python 3.10我用的是: pip install pycurl?7.45.1?cp310?cp310?win_amd64.whl 

4.7 视频转换项目

https://blog.csdn.net/thehunters/article/details/120988549?spm=1001.2101.3001.6650.5 

https://blog.csdn.net/woaidianqian/article/details/124280508?spm=1018.2226.3001.4187

https://blog.csdn.net/Jolen_xie/article/details/109270914?spm=1001.2101.3001.6650.2

 

 

 

 

 

 

 

 

 

 

 

[ 打印 ]
阅读 ()评论 (0)
评论
目前还没有任何评论
登录后才可评论.