Python脚本杂记

记录python脚本开发中的各种琐屑操作

持续更新ing

py剪切板、粘贴板

import pyperclip
str = pyperclip.paste()
pyperclip.copy(str)

检测文件是否为空

size = os.path.getsize(file_path)

将选中的多个文件夹中的文件全部合并到第一个文件夹里

#%%i是bat文件里表示参数,cmd命令行用%i。
for %%i in (%*) do move %%i\* %1
#%1代表拖入进来的第一个文件夹的名字,如果有空格,它会自动给你加双引号括起来
#%1-%9按顺序表示拖入的每一个文件、文件夹名称;%*表示所有
#如果是for中有多条语句
for %%i in%*) do ( ... )
@pause

win+R 运行输入 输入sysdm.cpl 快速打开环境变量界面

截图操作

其实是cmd操作,需要安装nircmd(我是2.81版本)更多nircmd的功能

(https://blog.csdn.net/hongkaihua1987/article/details/85050851)
os.system("nircmd savescreenshot {}{}.png 0 0 1920 1080".format(directory,10000+count))
#参数分别是绝对坐标(左上角为原点)的x,y,长度,宽度


#如果只想全屏截图(或者先全屏截图再多样化裁剪),可以使用pyautogui的screenshot函数
#im1 = pyautogui.screenshot()
#im1.save('my_screenshot.png')
#同时也可以用pyautogui的"按下组合按键"的hotkey函数,使用win+print screen键全屏截图

pyautogui 一些操作

import pyautogui #版本:PyAutoGUI==0.9.53
import os
import time

#获得一次鼠标坐标
currentMouseX, currentMouseY = pyautogui.position()
print(currentMouseX, currentMouseY)

#持续获得鼠标绝对坐标
while True:
    os.system("cls")
    print(pyautogui.position())
    time.sleep(0.1)
pyautogui.click(x=80, y=20)#单击绝对位置
pyautogui.press('f11')#按下键盘

参考其他大佬的总结

import pyautogui

# 获取当前屏幕分辨率
screenWidth, screenHeight = pyautogui.size()

# 获取当前鼠标位置
currentMouseX, currentMouseY = pyautogui.position()

# 2秒钟鼠标移动坐标为100,100位置  绝对移动
#pyautogui.moveTo(100, 100,2)
pyautogui.moveTo(x=100, y=100,duration=2, tween=pyautogui.linear)

#鼠标移到屏幕中央。
pyautogui.moveTo(screenWidth / 2, screenHeight / 2)

# 鼠标左击一次
#pyautogui.click()
# x 
# y 
# clicks 点击次数
# interval点击之间的间隔
# button 'left', 'middle', 'right' 对应鼠标 左 中 右或者取值(1, 2, or 3)
# tween 渐变函数
#
pyautogui.click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=pyautogui.linear)

# 鼠标相对移动 ,向下移动
#pyautogui.moveRel(None, 10)
pyautogui.moveRel(xOffset=None, yOffset=10,duration=0.0, tween=pyautogui.linear)


# 鼠标当前位置0间隔双击
#pyautogui.doubleClick()
pyautogui.doubleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=pyautogui.linear)

# 鼠标当前位置3击
#pyautogui.tripleClick()
pyautogui.tripleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=pyautogui.linear)

#右击
pyautogui.rightClick()

#中击
pyautogui.middleClick()

#  用缓动/渐变函数让鼠标2秒后移动到(500,500)位置
#  use tweening/easing function to move mouse over 2 seconds.
pyautogui.moveTo(x=500, y=500, duration=2, tween=pyautogui.easeInOutQuad)

#鼠标拖拽
pyautogui.dragTo(x=427, y=535, duration=3,button='left')

#鼠标相对拖拽
pyautogui.dragRel(xOffset=100,yOffset=100,duration=,button='left',mouseDownUp=False)

#鼠标移动到x=1796, y=778位置按下
pyautogui.mouseDown(x=1796, y=778, button='left')

#鼠标移动到x=2745, y=778位置松开(与mouseDown组合使用选中)
pyautogui.mouseUp(x=2745, y=778, button='left',duration=5)

#鼠标当前位置滚轮滚动
pyautogui.scroll()
#鼠标水平滚动(Linux)
pyautogui.hscroll()
#鼠标左右滚动(Linux)
pyautogui.vscroll()



#模拟输入信息
pyautogui.typewrite(message='Hello world!',interval=0.5)
#点击ESC
pyautogui.press('esc')
# 按住shift键
pyautogui.keyDown('shift')
# 放开shift键
pyautogui.keyUp('shift')
# 模拟组合热键
pyautogui.hotkey('ctrl', 'c')


#截图,全屏截图
im1 = pyautogui.screenshot()
im1.save('my_screenshot.png')

im2 = pyautogui.screenshot('my_screenshot2.png')

#在当前屏幕中查找指定图片(图片需要由系统截图功能截取的图)
coords = pyautogui.locateOnScreen('folder.png')
#获取定位到的图中间点坐标
x,y=pyautogui.center(coords)
#右击该坐标点
pyautogui.rightClick(x,y)


#保护措施,避免失控
pyautogui.FAILSAFE = True
#为所有的PyAutoGUI函数增加延迟。默认延迟时间是0.1秒。
pyautogui.PAUSE = 0.5


按键支持

提示信息
alert
#pyautogui.alert(‘This is an alert box.’,‘Test’)
pyautogui.alert(text=‘This is an alert box.’, title=‘Test’)
1
2

option
#pyautogui.confirm(‘Shall I proceed?’)
pyautogui.confirm(‘Enter option.’, buttons=[‘A’, ‘B’, ‘C’])
1
2

password
a = pyautogui.password(‘Enter password (text will be hidden)’)
print(a)

裁剪图片的代码

from PIL import Image #Pillow==8.3.1
cropped = img.crop((570, 0, 1355, 1080)) # (left, upper, right, lower)
cropped.save("newPicFileName")

视频提取MP3音轨的代码

第三方库:moviepy
from moviepy.editor import AudioFileClip
for f in self.filePath:
	
	my=AudioFileClip(f)
	f = f[:-4]+'.mp3'
	my.write_audiofile(f,fps=44100)
	print("{} 提取完成 ".format(f))

CMD运行时的一些参数

%~dp0表示当前目录(也就是bat文件所在的路径)

python %~dp0\aScript.py
@pause

%1 %2 %* 代表将文件拖入bat文件时的文件名,%* 代表所有

"%~dp0\any2png.exe" %*
:: 这个脚本表示将任意图片文件拖入此bat文件时,可以启动另一个写好的exe脚本,将他们全部转化为png格式。rem是注释,双冒号也是注释::
rem @pause

借助ff将视频转成mp4格式的代码
中间涉及到了字符串的切割和拼接

echo "%1 start"
set  output__=%1
set output_=%output__:~,-4%
set output=%output_%.mp4
::set output
ffmpeg -i %1 -c:v copy -c:a aac %output%
@pause

强制删除,操作是拖入bat文件

DEL /F /A /Q \\?\%1
RD /S /Q \\?\%1

tkinter的一些基础操作

import tkinter as tk
from tkinter import filedialog

#创建一个窗口实例
root = tk.Tk()
root.title("title")
root.geometry("800x400+300+300")
root.mainloop()#进入消息循环,类似于进程阻塞。这一句一般放最后

#各种组件

#文本显示
label_title = tk.Label(root,text="这是一个文字显示栏",anchor="w",width=55,font=('Hiragino Sans GB W3', 10)).pack()

#文本输入框
et_title=tk.Entry(root,show=None, width=40,font=('Hiragino Sans GB W3', 12))
et_title.pack()
self.et_title.insert(0,"アンソロジー")
#插入必须要指定第一个参数index
#同理,删除的时候也如此,'end'表示直到结尾
self.et_creator.delete(0,'end')

#如果生成就pack(指写在同一行),则返回值是None,所以如果一般要追加编辑一个组件,最好是额外写一行pack()

#按钮
bt_chooseCover = tk.Button(root,text="ChooseCover",font=('JetBrains Mono', 12),width=20,height=1,command=self.chooseCover)
bt_chooseCover.pack(side="bottom")
#上下左右四种方位,可以写字符串,也可以写tk.BOTTOM的预设值。写'left'则会出现在左边且往后叠加,左,次左……依次排开。

#退出按钮
self.esc_bt = tk.Button(self)
self.esc_bt['width'] = 15
self.esc_bt['height'] = 1
self.esc_bt["text"] = "关闭"
self.esc_bt["command"] = super().quit
self.esc_bt.pack(side="bottom")

#检测用户是否点击右上角,可以进行拦截或做退出前的额外操作,如删除临时文件,检测io是否关闭等
def beforeQuit(self):
	if os.path.exists("temp/"):
	  # shutil.rmtree("temp/")
	  os.system("rmdir /s/q temp")
	super().quit()


#按钮一般都会涉及:用户按下后处理相应功能,同是锁住按钮放置多按或不允许并发
#锁住
bt_chooseCover.config(state=tk.DISABLED)
#解开
bt_chooseCover.config(state=tk.NORMAL)
#config可以修改组件的参数,当然也可以直接用字典类型(map、dict)的方式访问
bt_chooseBookDir = tk.Button(root,font=('JetBrains Mono', 12))
bt_chooseBookDir['width'] = 20
bt_chooseBookDir['height'] = 1
bt_chooseBookDir["text"] = "chooseBook"
bt_chooseBookDir["command"] = getImgDirectory
bt_chooseBookDir.pack(side="top")


#listbox以及右侧的垂直滚动条
scrolly = tk.Scrollbar(root)
scrolly.pack(side=tk.RIGHT, fill=tk.Y)

self.listbox_en = tk.Listbox(root,yscrollcommand=scrolly.set,width = 120)
listbox_en.pack(side=tk.LEFT, padx=5, pady=5)
listbox_en.delete(0, "end")

scrolly.config(command=listbox_en.yview)


#选择目录 默认目录是可选参数
default_dir = r"D:\"
filePath = tk.filedialog.askdirectory(title=u'选择文件', initialdir=(os.path.expanduser(default_dir)))
if filePath == "":
	return
'''
os.path.expanduser函数的作用
在linux下面,一般如果你自己使用系统的时候,是可以用~来代表"/home/你的名字/"这个路径的.但是python是不认识~这个符号的,如果你写路径的时候直接写"~/balabala",程序是跑不动的.所以如果你要用~,你就应该用这个os.path.expanduser把~展开.
'''

#选择文件,注意文件类型的写法,是一个2元组,前项为类型名称如图片文件,后者可以是字符串也可以是多个字符串的组成的元组。
filedialog_title = "选择章节"
chapterIndexPath = filedialog.askopenfilename(title = filedialog_title,multiple=False,\
          initialdir = self.Images_dir,filetypes=[("图片文件",('.jpg','.png')),('All Files', '*')])
if chapterIndexPath== "":
	return


os操作的细枝末节

#不存在则创建目录
myPath = r'D:\dir1\dir2\dir3'
if not os.path.exists(myPath):
	os.mkdir(myPath)
#递归新建目录
os.makedirs(myPath)


#遍历一个目录下的文件,os.listdir()函数获得目录下所有文件的文件名:
for imgFile in os.listdir(Images_dir):
	pass

#cmd遍历文件夹
@echo off
::setlocal enabledelayedexpansion
for  %%x in (*) do (
    if not "%%x"=="demo.bat" 
	(
        set /a sum+=1
        rename "%%x" "!sum!.jpg"
	)
)
@pause
#以上是cmd遍历文件夹


#重命名
#新名称和旧名称可以都是绝对路径,也可以都是相对路径
os.rename(oldName , newName)

#获得文件所在父目录
parentDir = os.path.dirname()

(入门级)多线程操作

#创建并运行一个新的线程,第一个目标函数名,第二个位参数
参数用元组封装,如果参数只有一个,那记得带个逗号(元组方面的小细节)
_thread.start_new_thread(myFunction,(arg1,))
#函数可以用lambda表达式去调用一个函数。

在python里调用打包程序

#前提是安装了7z。当然,安装其他压缩软件也大抵会有对应的命令行指令
#什么?为何引入python的包?emmm。麻烦,命令行不爽么,速度还不慢。-mmt16参数指多核运行
cmd_7z = 'cd temp && 7z a "{}" -mmt16'.format(epubFileName)
# print(cmd_7z)
os.system(cmd_7z)

这里还指出了如何在一次os.system()函数的调用中执行两条逻辑有关联的命令的一种方法。os还提供了更多和cmd的交互的函数。下面引用一些其他大佬的笔记

1.os.system用来执行cmd指令,在cmd输出的内容会直接在控制台输出,返回结果为0表示执行成功
注意:os.system是简单粗暴的执行cmd指令,如果想获取在cmd输出的内容,是没办法获到的

2.如果想获取控制台输出的内容,那就用os.popen的方法了,popen返回的是一个file对象,跟open打开文件一样操作了,r是以读的方式打开
注意:os.popen() 方法用于从一个命令打开一个管道。在Unix,Windows中有效

import os

# popen返回文件对象,跟open操作一样
f = os.popen(r"python d:\hello.py", "r")

d = f.read()  # 读文件
print(d)
print(type(d))
f.close()

获取图片的宽和高

from PIL import Image

img = Image.open(coverImgPath)
coverWidth = img.size[0]
coverHeight = img.size[1]
img.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值