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
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
threading
import threading
def print_cube(num):
print ( "Cube: {}" . format (num * num * num))
def print_square(num):
print ( "Square: {}" . format (num * num))
if __name__ = = "__main__" :
t1 = threading.Thread(target = print_square, args = ( 10 ,))
t2 = threading.Thread(target = print_cube, args = ( 10 ,))
t1.start()
t2.start()
t1.join()
t2.join()
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
|