Python语言常用脚本

本文最后更新于 2024年8月12日 凌晨

Python 常用脚本

CH341A 模块

FTDI 模块

1
2
3
4
5
6
7
8
import ft4222
import ft4222.I2CMaster
# 需要在命令行使用以下命令,安装库
# pip install ft4222
# list devices
nbDev = ft4222.createDeviceInfoList()
for i in range(nbDev):
print(ft4222.getDeviceInfoDetail(i, False))

python venv

这是 Python 自带的包管理器,下面介绍常用命令。

1
2
3
4
5
6
7
8
# 创建环境
python -m venv /path/to/your/venv
# 激活环境 Windows
/path/to/your/venv/Scripts/activate
# 激活环境 Linux
source /path/to/your/venv/bin/activate
# 退出环境
deactivate

pip set

1
2
3
4
5
6
# 导出包
pip freeze > requirements.txt
# 导入包
pip install -r requirements.txt
# pip 安装到指定路径
pip install package_name -t /path/to/your/directory

pip package list

1
2
pip install vcdvcd
pip install python-lsp-server

文档

https://docs.python.org/zh-cn/3/download.html

https://peps.python.org/

LearnPython

模块

安装

1
2
3
4
pip install pyelftools PySimpleGUI lxml numpy chardet scipy matplotlib
pip install pyvisa pandas shutil
pip install shutil openpyxl

说明

1
2
# 用来暂停
os.system("pause")

打包应用

1
2
3
4
# -F 表示 打包为单个文件
# -w 表示为没有控制台
# -i .\favicon.ico 添加应用图标
pyinstaller.exe -F -w -i .\favicon.ico .\test.py

wav 250

import wave
import math
import array

音频参数

sample_rate = 44100 # 采样频率
duration = 60*10 # 音频时长(秒)

创建一个新的 WAV 文件

output_file = wave.open(‘output.wav’, ‘w’)
output_file.setnchannels(1) # 单声道
output_file.setsampwidth(2) # 2 字节,16 位
output_file.setframerate(sample_rate)

生成 250Hz 的音频数据

samples = array.array(‘h’, [0] _ (sample_rate _ duration))
amplitude = 2 ** 15 - 1 # 振幅

for i in range(len(samples)):
t = float(i) / sample*rate # 当前时间(秒)
samples[i] = int(amplitude * math.sin(2 _ math.pi _ 250 _ t))

将音频数据写入 WAV 文件

output_file.writeframes(samples)

关闭 WAV 文件

output_file.close()

import numpy as np
from scipy.io import wavfile
import wave

def generatesine_wave(freq, duration, filename): # 采样率
sample_rate = 44100 # 生成时间轴
t = np.linspace(0, duration, int(duration * sample
rate), endpoint=False) # 生成正弦波信号
wave_data = np.sin(2 * np.pi _ freq _ t) # 将信号归一化到 16 位范围内
wave_data_normalized = (wave_data * 32767).astype(np.int16)

# 创建并保存wav文件
with wave.open(filename, 'wb') as wav_file:
    wav_file.setnchannels(1)  # 设置为单声道
    wav_file.setsampwidth(2)  # 设置采样大小为2字节(16位)
    wav_file.setframerate(sample_rate)  # 设置采样率
    wav_file.writeframes(wave_data_normalized.tobytes())

示例:生成 1000Hz 频率,持续 2 秒的正弦波 wav 文件

generate_sine_wave(1000, 2, “sine_wave.wav”)

Excel

import as xl
workbook = xl.load_workbook(filename=”D:\Documents\aa.xlsx”)
workbook.sheetnames

pip

方法一: 打开网址,https://pypi.org/project/pip/#files

然后下载源码,解压,打开命令行,输入命令python setup.py install

输入pip --version,查看是否安装成功

方法二: 打开终端,执行py get-pip.py

安装模块: pip install module-name 例如: pip install pyelftools

  • juypter
  • pillow
  • requests
  • pyinstaller
1
2
# 参数解释: F只产生一个exe,w是不使用控制台,i是图标
pyinstaller -i xxx.icon -Fw demo.py

FAQ

Q: 指定版本运行脚本?
A: py -3.7 a.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#
import PySimpleGUI as sg
layout = [[sg.Text('Your typed chars appear here:'), sg.Text(size=(15,1), key='-OUTPUT-')],
[sg.Input(key='-IN-')],
[sg.Button('Show'), sg.Button('Exit')]]

window = sg.Window('Test', layout)

while True: # Event Loop
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
if event == 'Show':
# Update the "output" text element to be the value of "input" element
window['-OUTPUT-'].update(values['-IN-'])

window.close()
#
import os
import re

def batch_rename_files(directory, regex_pattern, new_text):
for filename in os.listdir(directory):
if re.match(regex_pattern, filename):
new_filename = re.sub(regex_pattern, new_text, filename)
os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))

# 指定目录和正则表达式
directory = "D:/aaaa"
regex_pattern = r'FPGA_240109b(.*)'
new_text = r'FPGA_240109(-3_6)\1' #\1指保留其他部分不变

# 执行批量重命名
batch_rename_files(directory, regex_pattern, new_text)


# 生成指定的bin
import os
import binascii
import random

file_path = 'example.bin'
# file_size = 0x3150
file_size = 1024*8

with open(file_path, 'wb') as f:
remaining_bytes = file_size
buffer_size = 1024 # 每次写入的字节数
while remaining_bytes > 0:
buffer = bytearray(random.getrandbits(8) for _ in range(min(buffer_size, remaining_bytes)))
f.write(buffer)
remaining_bytes -= buffer_size

# 音量
import PyAutoGUI
import time

while 1:
pyautogui.press('volumeup') #调大音量
time.sleep(5)
pyautogui.press('volumedown') #调小音量
time.sleep(5)
#pyautogui.press('volumemute') #静音

# 图形化
import PySimpleGUI as sg
# sg.popup('demo ok')
# sg.popup_ok_cancel('PopupOKCancel')
# sg.popup_error('PopupError') # Shows red error button
# sg.popup_timed('PopupTimed') # Automatically closes
# 例子:
text = sg.popup_get_file('Please enter a file name')


import PySimpleGUI as sg
import json
sg.set_options(font=('Arial Bold', 16))
layout = [
[sg.Text('Settings', justification='left')],
[sg.Text('User name', size=(10, 1), expand_x=True),
sg.Input(key='-USER-')],
[sg.Text('email ID', size=(10, 1), expand_x=True),
sg.Input(key='-ID-')],
[sg.Text('Role', size=(10, 1), expand_x=True),
sg.Input(key='-ROLE-')],
[sg.Button("LOAD"), sg.Button('SAVE'), sg.Button('Exit')]
]
window = sg.Window('User Settings Demo', layout, size=(715, 200))
# Event Loop
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
if event == 'LOAD':
f = open("settings.txt", 'r')
settings = json.load(f)
window['-USER-'].update(value=settings['-USER-'])
window['-ID-'].update(value=settings['-ID-'])
window['-ROLE-'].update(value=settings['-ROLE-'])
if event == 'SAVE':
settings = {'-USER-': values['-USER-'],
'-ID-': values['-ID-'],
'-ROLE-': values['-ROLE-']}
f = open("settings.txt", 'w')
json.dump(settings, f)
f.close()
window.close()




import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI as sg
import matplotlib
matplotlib.use('TkAgg')
fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
def draw_figure(canvas, figure):
tkcanvas = FigureCanvasTkAgg(figure, canvas)
tkcanvas.draw()
tkcanvas.get_tk_widget().pack(side='top', fill='both', expand=1)
return tkcanvas
layout = [[sg.Text('Plot test')],
[sg.Canvas(key='-CANVAS-')],
[sg.Button('Ok')]]
window = sg.Window('Matplotlib In PySimpleGUI', layout, size=(715, 500), finalize=True, element_justification='center', font='Helvetica 18')

# add the plot to the window
tkcanvas = draw_figure(window['-CANVAS-'].TKCanvas, fig)
event, values = window.read()
window.close()


import PySimpleGUI as psg
psg.set_options(font=('Arial Bold', 16))
layout = [
[psg.Text('Enter a num: '), psg.Input(key='-FIRST-')],
[psg.Text('Enter a num: '), psg.Input(key='-SECOND-')],
[psg.Text('Result : '), psg.Text(key='-OUT-')],
[psg.Button("Add"), psg.Button("Sub"), psg.Exit()],
]
window = psg.Window('Calculato1r', layout, size=(715, 180))
while True:
event, values = window.read()
print(event, values)
if event == "Add":
result = int(values['-FIRST-']) + int(values['-SECOND-'])
if event == "Sub":
result = int(values['-FIRST-']) - int(values['-SECOND-'])
window['-OUT-'].update(result)
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()

import PySimpleGUI as sg

# 定义布局
layout = [[sg.Text('Hello PySimpleGUI!')],
[sg.Button('OK')],
[sg.Button('continue')]]

# 创建窗口
window = sg.Window('aa', layout,icon = 'edit_icon.ico')

# 事件循环
while True:
event, values = window.read()

if event == sg.WINDOW_CLOSED or event == 'OK':
break
elif event == 'continue':
sg.popup("aaaaaaaaaaaaaa")

# 关闭窗口
window.close()

import PySimpleGUI as sg
import os

def main():
# 定义历史记录文件路径
history_file = 'history.txt'

# 创建布局
layout = [
[sg.Text('File 1:'), sg.InputText(key='file1'), sg.FileBrowse(initial_folder=get_last_path(history_file, 0))],
[sg.Text('File 2:'), sg.InputText(key='file2'), sg.FileBrowse(initial_folder=get_last_path(history_file, 1))],
[sg.Text('File 3:'), sg.InputText(key='file3'), sg.FileBrowse(initial_folder=get_last_path(history_file, 2))],
[sg.Text('File 4:'), sg.InputText(key='file4'), sg.FileBrowse(initial_folder=get_last_path(history_file, 3))],
[sg.Button('OK')],
]

# 创建窗口
window = sg.Window('File Selector', layout)

while True:
event, values = window.read()

if event == sg.WINDOW_CLOSED:
break

if event == 'OK':
# 保存历史记录
save_history(history_file, values['file1'], values['file2'], values['file3'], values['file4'])

# 弹出消息框
sg.popup('Hello World!')
break

window.close()

def get_last_path(history_file, index):
# 从历史记录文件中获取上次保存的路径
if os.path.exists(history_file):
with open(history_file, 'r') as file:
history = file.readlines()
if len(history) > index:
return history[index].strip()
return ''

def save_history(history_file, *paths):
# 将当前选择的路径保存到历史记录文件中
with open(history_file, 'w') as file:
for path in paths:
file.write(f'{path}\n')

if __name__ == '__main__':
main()


import PySimpleGUI as sg

sg.theme('Default1') # 设置当前主题
# 界面布局,将会按照列表顺序从上往下依次排列,二级列表中,从左往右依此排列
layout = [ [sg.Text('Some text on Row 1')],
[sg.Text('Enter something on Row 2'), sg.InputText()],
[sg.Button('Ok'), sg.Button('Cancel')] ]

# 创造窗口
window = sg.Window('Window Title', layout)
# 事件循环并获取输入值
while True:
event, values = window.read()
if event in (None, 'Cancel'): # 如果用户关闭窗口或点击`Cancel`
break
print('You entered ', values[0])

window.close()


import PySimpleGUI as sg

layout = [[sg.Text('My one-shot window.')],
[sg.InputText()],
[sg.Submit(), sg.Cancel()]]

window = sg.Window('Window Title', layout)

event, values = window.read()

window.close()
text_input = values[0]
sg.popup('You entered', text_input) # 弹出窗口



import PySimpleGUI as sg
layout = [[sg.Text('Your typed chars appear here:'), sg.Text(size=(15,1), key='-OUTPUT-')],
[sg.Input(key='-IN-')],
[sg.Button('Show'), sg.Button('Exit')]]

window = sg.Window('Pattern 2B', layout)

while True: # Event Loop
event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
if event == 'Show':
# Update the "output" text element to be the value of "input" element
window['-OUTPUT-'].update(values['-IN-'])

window.close()

import PySimpleGUI as sg

layout = [[sg.Text('A custom progress meter')],
[sg.ProgressBar(1000, orientation='h', size=(20, 20), key='progressbar')],
[sg.Cancel()]]

window = sg.Window('Custom Progress Meter', layout)
progress_bar = window['progressbar']
# loop that would normally do something useful
for i in range(1000):
# check to see if the cancel button was clicked and exit loop if clicked
event, values = window.read(timeout=10)
if event == 'Cancel' or event is None:
break
# update bar with loop value +1 so that bar eventually reaches the maximum
progress_bar.UpdateBar(i + 1)
# done with loop... need to destroy the window as it's still open
window.close()

import PySimpleGUI as sg
sg.theme('Default1')
text = sg.popup_get_file('Please enter a file name',no_window=False)
print(text)

import PySimpleGUI as sg
theme_name_list = sg.theme_list()
sg.theme_previewer()
sg.theme('Default1')
layout = [[sg.Text('Theme Browser')],
[sg.Text('Click a Theme color to see demo window')],
[sg.Listbox(values=sg.theme_list(), size=(20, 12), key='-LIST-', enable_events=True)],
[sg.Button('Exit')]]
window = sg.Window('Theme Browser', layout)

while True: # Event Loop
event, values = window.read()
if event in (None, 'Exit'):
break
sg.theme(values['-LIST-'][0])
sg.popup_get_text('This is {}'.format(values['-LIST-'][0]))

window.close()



import PySimpleGUI as psg
text = psg.popup_get_text('Enter your name', title="Textbox")
print ("You entered: ", text)
file=psg.popup_get_file('Select a file', title="File selector")
print ("File selected", file)
folder=psg.popup_get_folder('Get folder', title="Folder selector")
print ("Folder selected",folder)
ch = psg.popup_yes_no("Do you want to Continue?", title="YesNo")
print ("You clicked", ch)
ch = psg.popup_ok_cancel("Press Ok to proceed", "Press cancel to stop", title="OkCancel")
if ch=="OK":
print ("You pressed OK")
if ch=="Cancel":
print ("You pressed Cancel")
psg.popup_no_buttons('You pressed', ch, non_blocking=True)
psg.popup_auto_close('This window will Autoclose')



import PySimpleGUI as psg
layout = [
[psg.Text('Name '), psg.Input()],
[psg.Text('Address '), psg.Input()],
[psg.Text('Email ID '), psg.Input()],
[psg.OK(), psg.Exit()]
]
window = psg.Window('Form', layout)
while True:
event, values = window.read()
if event == psg.WIN_CLOSED or event == 'Exit':
break
print (event, values)
window.close()

import PySimpleGUI as psg
psg.set_options(font=('Arial Bold', 16))
layout = [
[psg.Text('Name ', size=(15, 1)),
psg.Input(key='-NM-', expand_x=True)],
[psg.Text('Address ', size=(15, 1)),
psg.Input(key='-AD-', expand_x=True)],
[psg.Text('Email ID ', size=(15, 1)),
psg.Input(key='-ID-', expand_x=True)],
[psg.Text('You Entered '), psg.Text(key='-OUT-')],
[psg.OK(), psg.Exit()],
]
window = psg.Window('Form', layout, size=(715, 200))
while True:
event, values = window.read()
print(event, values)
out = values['-NM-'] + ' ' + values['-AD-'] + ' ' + values['-ID-']
window['-OUT-'].update(out)
if event == psg.WIN_CLOSED or event == 'Exit':
break
window.close()

FTDI module

1
2
3
4
5
6
7
8
9
10
11
import ft4222
import ft4222.I2CMaster


# 需要在命令行使用以下命令,安装库
# pip install ft4222

# list devices
nbDev = ft4222.createDeviceInfoList()
for i in range(nbDev):
print(ft4222.getDeviceInfoDetail(i, False))

生成音频

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# wav 250
import wave
import math
import array

# 音频参数
sample_rate = 44100 # 采样频率
duration = 60*1 # 音频时长(秒)

# 创建一个新的WAV文件
output_file = wave.open('output.wav', 'w')
output_file.setnchannels(1) # 单声道
output_file.setsampwidth(2) # 2字节,16位
output_file.setframerate(sample_rate)

# 生成250Hz的音频数据
samples = array.array('h', [0] * (sample_rate * duration))
amplitude = 2 ** 15 - 1 # 振幅

for i in range(len(samples)):
t = float(i) / sample_rate # 当前时间(秒)
samples[i] = int(amplitude * math.sin(2 * math.pi * 250 * t))

# 将音频数据写入WAV文件
output_file.writeframes(samples)

# 关闭WAV文件
output_file.close()

打包的时候使用:

1
pyinstaller --icon=edit_icon.ico --noconsole  --onefile demo.py

Python语言常用脚本
https://blog.zimablue.fun/2024/08/11/Python常用脚本/
作者
zimablue1996
发布于
2024年8月11日
许可协议