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
|