Automate the Boring Stuff Book Note
Automate the Boring Stuff with Python is a introductory book of Python and some common daily usage of it. It contains lots of good examples. This post lists some notes of the book.
String partition
1 | 'Hello, world!'.partition('o') |
Copy and paste strings with pyperclip module
1 | import pyperclip |
Regular expression
Some examples:
1 | # If you would like to retrieve all the groups at once, use the groups() method |
Character classes
Shorthand character class | Represents |
---|---|
Any numeric digit from 0 to 9. | |
Any character that is not a numeric digit from 0 to 9. | |
Any letter, numeric digit, or the underscore character. (Think of this as matching “word” characters.) | |
Any character that is not a letter, numeric digit, or the underscore character. | |
Any space, tab, or newline character. | |
Any character that is not a space, tab, or newline. |
Input validation with PYINPUTPLUS module
1 | import pyinputplus as pyip |
You can also passing a custom validation function to
inputCustom()
. The custom function should have the
following properties:
- Accepts a single string argument of what the user entered
- Raises an exception if the string fails validation
- Returns
None
or do not return if theinputCustom()
should return the string unchanged - Otherwise return a non-
None
value. - This function shall be passed as the first argument to
inputCustom()
Portable paths
1 | from pathlib import Path |
Write and read variables in file
It can be done with shelve
module.
1 | import shelve |
Or with the pprint.pformat()
function.
1 | import pprint |
Organizing files
copy, move and rename files like in shell with
shutil
(shell utilities) module.1
2
3'spam.txt', p / 'some_folder') shutil.copy(p /
'spam', p / 'spam_backup') shutil.copytree(p /
'C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt') shutil.move(permanently deleting files or folders.
os.unlink(file)
deletes a file.os.rmdir(folder)
deletes an empty folder.shutil.rmtree(folder)
deletes a folder and everything within it.
safe deletion with
send2trash
module.managing
zip
files withzipfile
modulecreation
1
2
3
4import zipfile
'new.zip', 'w') newZip = zipfile.ZipFile(
'spam.txt', compress_type=zipfile.ZIP_DEFLATED) newZip.write(
newZip.close()extraction
1
2
3
4
5
6
7'example.zip') exampleZip = zipfile.ZipFile(Path.home() /
'spam.txt') exampleZip.extract(
'C:\\spam.txt'
'spam.txt', 'C:\\some\\new\\folders') exampleZip.extract(
'C:\\some\\new\\folders\\spam.txt'
exampleZip.extractall()
exampleZip.close()read
1
2
3
4
5
6
7
8'example.zip') exampleZip = zipfile.ZipFile(Path.home() /
exampleZip.namelist()
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
'spam.txt') spamInfo = exampleZip.getinfo(
spamInfo.file_size
13908
spamInfo.compress_size
3828
Assertions
Example
1
2
3
4
5
6
7
826, 57, 92, 54, 22, 15, 17, 80, 47, 73] ages = [
ages.reverse()
ages
[73, 47, 80, 17, 15, 22, 54, 92, 57, 26]
assert ages[0] <= ages[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionErrorUnlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash
Assertions are for programmer errors, not user errors
Logging
Example
1
2
3
4
5
6
7
8
9
10
11
12import logging
format=' %(asctime)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.DEBUG,
'Some debugging details.') logging.debug(
2019-05-18 19:04:26,901 - DEBUG - Some debugging details.
'The logging module is working.') logging.info(
2019-05-18 19:04:35,569 - INFO - The logging module is working.
'An error message is about to be logged.') logging.warning(
2019-05-18 19:04:56,843 - WARNING - An error message is about to be logged.
'An error has occurred.') logging.error(
2019-05-18 19:05:07,737 - ERROR - An error has occurred.
'The program is unable to recover!') logging.critical(
2019-05-18 19:05:45,794 - CRITICAL - The program is unable to recover!Logging level from lowest to highest
logging.debug()
logging.info()
logging.warning()
logging.error()
logging.critical()
Disable logging
1
logging.disable(logging.CRITICAL)
Logging to file
1
2import logging
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
Download a web page
With
requests.get()
function1
2
3
4
5
6
7
8
9
10import requests
'https://automatetheboringstuff.com/files/rj.txt') res = requests.get(
type(res)
<class 'requests.models.Response'>
res.status_code == requests.codes.ok
True
len(res.text)
178981
print(res.text[:80])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare...Error handling
1
2
3
4
5
6import requests
res = requests.get('https://inventwithpython.com/page_that_does_not_exist')
try:
res.raise_for_status()
except Exception as exc:
print('There was a problem: %s' % (exc))Save to file
1
2
3
4
5
6
7'https://automatetheboringstuff.com/files/rj.txt') res = requests.get(
open('RomeoAndJuliet.txt', 'wb') playFile =
for chunk in res.iter_content(100000):
playFile.write(chunk)
100000
78981
playFile.close()
Parsing HTML with BS4
module
Example HTML
1
2
3
4
5
6
7
8
9<!-- This is the example.html example file. -->
<html><head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="https://
inventwithpython.com">my website</a>.</p>
<p class="slogan">Learn Python the easy way!</p>
<p>By <span id="author">Al Sweigart</span></p>
</body></html>Start
1
2
3
4
5
6
7
8
9
10
11import requests, bs4
'https://nostarch.com') res = requests.get(
res.raise_for_status()
'html.parser') noStarchSoup = bs4.BeautifulSoup(res.text,
type(noStarchSoup)
<class 'bs4.BeautifulSoup'>
open('example.html') exampleFile =
'html.parser') exampleSoup = bs4.BeautifulSoup(exampleFile,
type(exampleSoup)
<class 'bs4.BeautifulSoup'>Find an element with
select()
method1
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
38open('example.html') exampleFile =
'html.parser') exampleSoup = bs4.BeautifulSoup(exampleFile.read(),
'#author') elems = exampleSoup.select(
type(elems) # elems is a list of Tag objects.
<class 'list'>
len(elems)
1
type(elems[0])
<class 'bs4.element.Tag'>
str(elems[0]) # The Tag object as a string.
'<span id="author">Al Sweigart</span>'
0].getText() elems[
'Al Sweigart'
0].attrs elems[
{'id': 'author'}
'p') pElems = exampleSoup.select(
str(pElems[0])
'<p>Download my <strong>Python</strong> book from <a href="https://
inventwithpython.com">my website</a>.</p>'
0].getText() pElems[
'Download my Python book from my website.'
str(pElems[1])
'<p class="slogan">Learn Python the easy way!</p>'
1].getText() pElems[
'Learn Python the easy way!'
str(pElems[2])
'<p>By <span id="author">Al Sweigart</span></p>'
2].getText() pElems[
'By Al Sweigart'
'span')[0] spanElem = soup.select(
str(spanElem)
'<span id="author">Al Sweigart</span>'
'id') spanElem.get(
'author'
'some_nonexistent_addr') == None spanElem.get(
True
spanElem.attrs
{'id': 'author'}
Web crawler with selenium-controlled browser
Start
1
2
3
4
5from selenium import webdriver
browser = webdriver.Firefox()
type(browser)
<class 'selenium.webdriver.firefox.webdriver.WebDriver'>
'https://inventwithpython.com') browser.get(Find element
1
2elem = browser.find_element_by_class_name(' cover-thumb')
print('Found <%s> element with that class name!' % (elem.tag_name))Clicking
1
2
3
4'Read Online for Free') linkElem = browser.find_element_by_link_text(
type(linkElem)
<class 'selenium.webdriver.remote.webelement.FirefoxWebElement'>
linkElem.click()Filling out and submitting forms
1
2
3
4
5'user_name) userElem = browser.find_element_by_id(
>>> userElem.send_keys('your_username_here')
>>> passwordElem = browser.find_element_by_id('user_pass')
>>> passwordElem.send_keys('your_password_here')
>>> passwordElem.submit()Send special keys
1
2
3
4'html') htmlElem = browser.find_element_by_tag_name(
# scrolls to bottom htmlElem.send_keys(Keys.END)
# clicks the refresh button browser.refresh()
# scrolls to top htmlElem.send_keys(Keys.HOME)
Manage Excel documents
with OpenPyXL
Opening
1
2
3
4import openpyxl
'example.xlsx') wb = openpyxl.load_workbook(
type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>Getting sheet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16wb.sheetnames
['Sheet1', 'Sheet2', 'Sheet3']
'Sheet3'] sheet = wb[
sheet
<Worksheet "Sheet3">
type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
sheet.title
'Sheet3'
anotherSheet = wb.active
anotherSheet
<Worksheet "Sheet1">
sheet.max_row
7
sheet.max_column
3Getting cells
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'Sheet1'] sheet = wb[
'A1'] sheet[
<Cell 'Sheet1'.A1>
'A1'].value sheet[
datetime.datetime(2015, 4, 5, 13, 34, 2)
'B1'] 1 c = sheet[
c.value
'Apples'
'Row %s, Column %s is %s' % (c.row, c.column, c.value)
'Row 1, Column B is Apples'
'Cell %s is %s' % (c.coordinate, c.value)
'Cell B1 is Apples'
'C1'].value sheet[
73
1, column=2) sheet.cell(row=
<Cell 'Sheet1'.B1>
1, column=2).value sheet.cell(row=
'Apples'
900) openpyxl.utils.get_column_letter(
'AHP'
'AA') openpyxl.utils.column_index_from_string(
27
tuple(sheet['A1':'C3'])
((<Cell 'Sheet1'.A1>, <Cell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>), (<Cell 'Sheet1'.A2>, <Cell 'Sheet1'.B2>, <Cell 'Sheet1'.C2>), (<Cell 'Sheet1'.A3>, <Cell 'Sheet1'.B3>, <Cell 'Sheet1'.C3>))
'A1'] = 'Hello, world!' sheet[
'A1'].value sheet[
'Hello, world!'Creating and removing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21wb = openpyxl.Workbook()
wb.sheetnames
['Sheet']
wb.create_sheet()
<Worksheet "Sheet1">
wb.sheetnames
['Sheet', 'Sheet1']
0, title='First Sheet') wb.create_sheet(index=
<Worksheet "First Sheet">
wb.sheetnames
['First Sheet', 'Sheet', 'Sheet1']
2, title='Middle Sheet') wb.create_sheet(index=
<Worksheet "Middle Sheet">
wb.sheetnames
['First Sheet', 'Sheet', 'Middle Sheet', 'Sheet1']
wb.sheetnames
['First Sheet', 'Sheet', 'Middle Sheet', 'Sheet1']
del wb['Middle Sheet']
del wb['Sheet1']
wb.sheetnames
['First Sheet', 'Sheet']Formula
1
2
3'B9'] = '=SUM(B1:B8)' sheet[
'A1:D3') sheet.merge_cells(
'writeFormula.xlsx') wb.save(Setting size
1
21].height = 70 sheet.row_dimensions[
'B'].width = 20 sheet.column_dimensions[There are similar API for google sheets
Manage PDF
Extract text
1
2
3
4
5
6
7
8
9import PyPDF2
open('meetingminutes.pdf', 'rb') pdfFileObj =
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pdfReader.numPages
19
0) pageObj = pdfReader.getPage(
pageObj.extractText()
'BOARD of ELEMENTARY and SECONDARY EDUCATION'
pdfFileObj.close()Decrypting
1
2
3
4
5
6
7
8
9
10open('encrypted.pdf', 'rb')) pdfReader = PyPDF2.PdfFileReader(
pdfReader.isEncrypted
True
'rosebud') pdfReader.decrypt(
1
0) pageObj = pdfReader.getPage(
'swordfish') pdfWriter.encrypt(
open('encryptedminutes.pdf', 'wb') resultPdf =
pdfWriter.write(resultPdf)
resultPdf.close()Creating
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import PyPDF2
open('meetingminutes.pdf', 'rb') pdf1File =
open('meetingminutes2.pdf', 'rb') pdf2File =
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
pdfWriter = PyPDF2.PdfFileWriter()
0) page = pdf1Reader.getPage(
90) page.rotateClockwise(
for pageNum in range(pdf1Reader.numPages):
pageObj = pdf1Reader.getPage(pageNum)
pdfWriter.addPage(pageObj)
for pageNum in range(pdf2Reader.numPages):
pageObj = pdf2Reader.getPage(pageNum)
pdfWriter.addPage(pageObj)
open('combinedminutes.pdf', 'wb') pdfOutputFile =
pdfWriter.write(pdfOutputFile)
pdfOutputFile.close()
pdf1File.close()
pdf2File.close()Overlaying pages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import PyPDF2
open('meetingminutes.pdf', 'rb') minutesFile =
pdfReader = PyPDF2.PdfFileReader(minutesFile)
0) minutesFirstPage = pdfReader.getPage(
open('watermark.pdf', 'rb')) pdfWatermarkReader = PyPDF2.PdfFileReader(
0)) minutesFirstPage.mergePage(pdfWatermarkReader.getPage(
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(minutesFirstPage)
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
open('watermarkedCover.pdf', 'wb') resultPdfFile =
pdfWriter.write(resultPdfFile)
minutesFile.close()
resultPdfFile.close()
Manage Word documents
Create
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import docx
doc = docx.Document()
'Hello world!') doc.add_paragraph(
<docx.text.Paragraph object at 0x000000000366AD30>
'This is a second paragraph.') paraObj1 = doc.add_paragraph(
'This is a yet another paragraph.') paraObj2 = doc.add_paragraph(
' This text is being added to the second paragraph.') paraObj1.add_run(
<docx.text.Run object at 0x0000000003A2C860>
'Header 0', 0) doc.add_heading(
<docx.text.Paragraph object at 0x00000000036CB3C8>
'Header 1', 1) doc.add_heading(
<docx.text.Paragraph object at 0x00000000036CB630>
'Header 2', 2) doc.add_heading(
<docx.text.Paragraph object at 0x00000000036CB828>
'Header 3', 3) doc.add_heading(
<docx.text.Paragraph object at 0x00000000036CB2E8>
'Header 4', 4) doc.add_heading(
<docx.text.Paragraph object at 0x00000000036CB3C8>
'zophie.png', width=docx.shared.Inches(1), height=docx.shared.Cm(4)) doc.add_picture(
<docx.shape.InlineShape object at 0x00000000036C7D30>
'multipleParagraphs.docx') doc.save(
Manage CSV files
Reading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import csv
open('example.csv') exampleFile =
exampleReader = csv.reader(exampleFile)
list(exampleReader) exampleData =
exampleData
[['4/5/2015 13:34', 'Apples', '73'], ['4/5/2015 3:41', 'Cherries', '85'],
['4/6/2015 12:46', 'Pears', '14'], ['4/8/2015 8:59', 'Oranges', '52'],
['4/10/2015 2:07', 'Apples', '152'], ['4/10/2015 18:10', 'Bananas', '23'],
['4/10/2015 2:40', 'Strawberries', '98']]
0][0] exampleData[
'4/5/2015 13:34'
0][1] exampleData[
'Apples'
0][2] exampleData[
'73'
1][1] exampleData[
'Cherries'
6][1] exampleData[
'Strawberries'Writing
1
2
3
4
5
6
7
8
9
10import csv
open('output.csv', 'w', newline='') outputFile =
'\t', lineterminator='\n\n') outputWriter = csv.writer(outputFile, delimiter=
'spam', 'eggs', 'bacon', 'ham']) outputWriter.writerow([
21
'Hello, world!', 'eggs', 'bacon', 'ham']) outputWriter.writerow([
32
1, 2, 3.141592, 4]) outputWriter.writerow([
16
outputFile.close()Better reader and writer
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
27import csv
open('example.csv') exampleFile =
'time', 'name', exampleDictReader = csv.DictReader(exampleFile, [
'amount'])
for row in exampleDictReader:
print(row['time'], row['name'], row['amount'])
...
4/5/2015 13:34 Apples 73
4/5/2015 3:41 Cherries 85
4/6/2015 12:46 Pears 14
4/8/2015 8:59 Oranges 52
4/10/2015 2:07 Apples 152
4/10/2015 18:10 Bananas 23
4/10/2015 2:40 Strawberries 98
open('output.csv', 'w', newline='') outputFile =
'Name', 'Pet', 'Phone']) outputDictWriter = csv.DictWriter(outputFile, [
outputDictWriter.writeheader()
'Name': 'Alice', 'Pet': 'cat', 'Phone': '555- outputDictWriter.writerow({
1234'})
20
'Name': 'Bob', 'Phone': '555-9999'}) outputDictWriter.writerow({
15
'Phone': '555-5555', 'Name': 'Carol', 'Pet': outputDictWriter.writerow({
'dog'})
20
outputFile.close()
Manage JSON data
Reading
1
2
3
4
5
6'{"name": "Zophie", "isCat": true, "miceCaught": 0, stringOfJsonData =
"felineIQ": null}'
import json
jsonDataAsPythonValue = json.loads(stringOfJsonData)
jsonDataAsPythonValue
{'isCat': True, 'miceCaught': 0, 'name': 'Zophie', 'felineIQ': None}Writing
1
2
3
4
5
6'isCat': True, 'miceCaught': 0, 'name': 'Zophie', pythonValue = {
'felineIQ': None}
import json
stringOfJsonData = json.dumps(pythonValue)
stringOfJsonData
'{"isCat": true, "felineIQ": null, "miceCaught": 0, "name": "Zophie" }'
Date and time
Datatime
module1
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
28import datetime
datetime.datetime.now()
datetime.datetime(2019, 2, 27, 11, 10, 49, 55, 53)
2019, 10, 21, 16, 29, 0) dt = datetime.datetime(
dt.year, dt.month, dt.day
(2019, 10, 21)
dt.hour, dt.minute, dt.second
(16, 29, 0)
2019, 10, 31, 0, 0, 0) halloween2019 = datetime.datetime(
2020, 1, 1, 0, 0, 0) newyears2020 = datetime.datetime(
2019, 10, 31, 0, 0, 0) oct31_2019 = datetime.datetime(
halloween2019 == oct31_2019
True
halloween2019 > newyears2020
False
newyears2020 > halloween2019
True
newyears2020 != oct31_2019
True
11, hours=10, minutes=9, seconds=8) delta = datetime.timedelta(days=
delta.days, delta.seconds, delta.microseconds
(11, 36548, 0)
delta.total_seconds()
986948.0
str(delta)
'11 days, 10:09:08'
Multithreading
Example:
1
2
3
4
5
6
7
8
9
10
11import threading, time
print('Start of program.')
def takeANap():
time.sleep(5)
print('Wake up!')
threadObj = threading.Thread(target=takeANap)
threadObj.start()
print('End of program.')Passing arguments:
1
2
3
4
5import threading
print, args=['Cats', 'Dogs', 'Frogs'], threadObj = threading.Thread(target=
kwargs={'sep': ' & '})
threadObj.start()
Cats & Dogs & FrogsSynchronizing
1
2
3for downloadThread in downloadThreads:
downloadThread.join()
print('Done.')Launch other programs
1
2
3
4
5import subprocess
'C:\\Windows\\System32\\calc.exe') subprocess.Popen(
<subprocess.Popen object at 0x0000000003055A58>
'C:\\Windows\\notepad.exe', 'C:\\Users\Al\\hello.txt']) subprocess.Popen([
<subprocess.Popen object at 0x00000000032DCEB8>
Manipulate images
Read
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16from PIL import Image
open('zophie.png') catIm = Image.
catIm.size
(816, 1088)
width, height = catIm.size
width
816
height
1088
catIm.filename
'zophie.png'
format catIm.
'PNG'
catIm.format_description
'Portable network graphics'
'zophie.jpg') catIm.save(Creating
1
2
3
4
5from PIL import Image
'RGBA', (100, 200), 'purple') im = Image.new(
'purpleImage.png') im.save(
'RGBA', (20, 20)) im2 = Image.new(
'transparentImage.png') im2.save(Cropping
1
2
3
4from PIL import Image
open('zophie.png') catIm = Image.
335, 345, 565, 560)) croppedIm = catIm.crop((
'cropped.png') croppedIm.save(Copying and pasting
1
2
3
4
5
6
7
8
9
10from PIL import Image
open('zophie.png') catIm = Image.
catCopyIm = catIm.copy()
335, 345, 565, 560)) faceIm = catIm.crop((
faceIm.size
(230, 215)
0, 0)) catCopyIm.paste(faceIm, (
400, 500)) catCopyIm.paste(faceIm, (
'pasted.png') catCopyIm.save(Resizing
1
2
3
4
5
6
7from PIL import Image
open('zophie.png') catIm = Image.
width, height = catIm.size
int(width / 2), int(height / 2))) quartersizedIm = catIm.resize((
'quartersized.png') quartersizedIm.save(
300)) svelteIm = catIm.resize((width, height +
'svelte.png') svelteIm.save(Rotating and flipping
1
2
3
4
5
6
7from PIL import Image
open('zophie.png') catIm = Image.
90).save('rotated90.png') catIm.rotate(
180).save('rotated180.png') catIm.rotate(
270).save('rotated270.png') catIm.rotate(
'horizontal_flip.png') catIm.transpose(Image.FLIP_LEFT_RIGHT).save(
'vertical_flip.png') catIm.transpose(Image.FLIP_TOP_BOTTOM).save(Drawing picture
1
2
3
4
5
6
7
8
9
10
11from PIL import Image, ImageDraw
'RGBA', (200, 200), 'white') im = Image.new(
draw = ImageDraw.Draw(im)
0, 0), (199, 0), (199, 199), (0, 199), (0, 0)], fill='black') draw.line([(
20, 30, 60, 60), fill='blue') draw.rectangle((
120, 30, 160, 60), fill='red') draw.ellipse((
57, 87), (79, 62), (94, 85), (120, 90), (103, 113)), fill='brown') draw.polygon(((
for i in range(100, 200, 10):
draw.line([(i, 0), (200, i - 100)], fill='green')
'drawing.png') im.save(Drawing text
1
2
3
4
5
6
7
8
9from PIL import Image, ImageDraw, ImageFont
import os
'RGBA', (200, 200), 'white') im = Image.new(
draw = ImageDraw.Draw(im)
20, 150), 'Hello', fill='purple') draw.text((
'FONT_FOLDER' # e.g. ‘/Library/Fonts' fontsFolder =
'arial.ttf'), 32) arialFont = ImageFont.truetype(os.path.join(fontsFolder,
100, 150), 'Howdy', fill='gray', font=arialFont) draw.text((
'text.png') im.save(
Control mouse
Get screen information
1
2
3
4
5
6
7
8import pyautogui
wh = pyautogui.size()
wh
Size(width=1920, height=1080)
0] wh[
1920
wh.width
1920Move the mouse
1
2
3
4
5
6
7
8
9
10
11
12import pyautogui
for i in range(10):
100, 100, duration=0.25) pyautogui.moveTo(
200, 100, duration=0.25) pyautogui.moveTo(
200, 200, duration=0.25) pyautogui.moveTo(
100, 200, duration=0.25) pyautogui.moveTo(
for i in range(10):
100, 0, duration=0.25) # right pyautogui.move(
0, 100, duration=0.25) # down pyautogui.move(
100, 0, duration=0.25) # left pyautogui.move(-
0, -100, duration=0.25) # up pyautogui.move(Control mouse
1
2
3
4
5# Get current mouse position pyautogui.position()
Point(x=377, y=481)
10, 5) # Move mouse to (10, 5) and click. pyautogui.click(
0, duration=0.2) # Drag right pyautogui.drag(distance,
200) # Scrolling pyautogui.scroll(
Manage windows
Getting screenshoot
1
2import pyautogui
im = pyautogui.screenshot()Manipulating windows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import pyautogui
fw = pyautogui.getActiveWindow()
# Gets the current width of the window. fw.width
1669
# Gets the current position of the window. fw.topleft
(174, 153)
1000 # Resizes the width. fw.width =
800, 400) # Moves the window. fw.topleft = (
# Returns True if window is maximized. fw.isMaximized
False
# Returns True if window is minimized. fw.isMinimized
False
# Returns True if window is the active window. fw.isActive
True
# Maximizes the window. fw.maximize()
fw.isMaximized
True
# Undoes a minimize/maximize action. fw.restore()
Control the keyboard
Send a string
1
100, 200); pyautogui.write('Hello, world!') pyautogui.click(
Send keys
1
'a', 'b', 'left', 'left', 'X', 'Y']) pyautogui.write([
Pressing and releasing
1
'shift'); pyautogui.press('4'); pyautogui.keyUp('shift') pyautogui.keyDown(