Python

Python Automation Modules documentation

Keyboard and Mouse Control

  
     import pyautogui
     screenWidth, screenHeight = pyautogui.size() # Returns two integers, the width and height of the screen. (The primary monitor, in multi-monitor setups.)
     currentMouseX, currentMouseY = pyautogui.position() # Returns two integers, the x and y of the mouse cursor's current position.
     pyautogui.moveTo(100, 150) # Move the mouse to the x, y coordinates 100, 150.
     pyautogui.click() # Click the mouse at its current location.
     pyautogui.click(200, 220) # Click the mouse at the x, y coordinates 200, 220.
     pyautogui.move(None, 10)  # Move mouse 10 pixels down, that is, move the mouse relative to its current position.
     pyautogui.doubleClick() # Double click the mouse at the
     pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.
     pyautogui.write('Hello world!', interval=0.25)  # Type with quarter-second pause in between each key.
     pyautogui.press('esc') # Simulate pressing the Escape key.
     pyautogui.keyDown('shift')
     pyautogui.write(['left', 'left', 'left', 'left', 'left', 'left'])
     pyautogui.keyUp('shift')
     pyautogui.hotkey('ctrl', 'c')

Display Message Boxes

     import pyautogui
     pyautogui.alert('This is an alert box.')
    'OK'
     pyautogui.confirm('Shall I proceed?')
    'Cancel'
     pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C'])
    'B'
     pyautogui.prompt('What is your name?')
    'Al'
     pyautogui.password('Enter password (text will be hidden)')
    'swordfish'

Screenshot Functions

(PyAutoGUI uses Pillow for image-related features.)

     import pyautogui
     im1 = pyautogui.screenshot()
     im1.save('my_screenshot.png')
     im2 = pyautogui.screenshot('my_screenshot2.png')

You can also locate where an image is on the screen:

     import pyautogui
     button7location = pyautogui.locateOnScreen('button.png') # returns (left, top, width, height) of matching region
     button7location
    (1416, 562, 50, 41)
     buttonx, buttony = pyautogui.center(button7location)
     buttonx, buttony
    (1441, 582)
     pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

Make Virtual Assistant with python

The locateCenterOnScreen() function returns the center of this match region:

     import pyautogui
     buttonx, buttony = pyautogui.locateCenterOnScreen('button.png') # returns (x, y) of matching region
     buttonx, buttony
    (1441, 582)
     pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found
automation with python

os Module

  • os.name
  • os.environ
  • os.chdir()
  • os.getcwd()
  • os.getenv()
  • os.putenv()
  • os.mkdir()
  • os.makedirs()
  • os.remove()
  • os.rename()
  • os.rmdir()
  • os.startfile()
  • os.walk()
  • os.path
import os

os.name

>>> import os
>>> os.name

os.environ, os.getenv() and os.putenv()

import os
os.environ
{'ALLUSERSPROFILE': 'C:\\ProgramData',
 'APPDATA': 'C:\\Users\\mike\\AppData\\Roaming',
 'CLASSPATH': '.;C:\\Program Files\\QuickTime\\QTSystem\\QTJava.zip',
 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files',
 'COMPUTERNAME': 'MIKE-PC',
 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe',
 'FP_NO_HOST_CHECK': 'NO',
 'HOMEDRIVE': 'C:',
 'HOMEPATH': '\\Users\\mike',
 'LOCALAPPDATA': 'C:\\Users\\mike\\AppData\\Local',
 'LOGONSERVER': '\\\\MIKE-PC',
 'NUMBER_OF_PROCESSORS': '2',
 'OS': 'Windows_NT',
 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',
 'PROCESSOR_ARCHITECTURE': 'x86',
 'PROCESSOR_IDENTIFIER': 'x86 Family 6 Model 15 Stepping 13, GenuineIntel',
 'PROCESSOR_LEVEL': '6',
 'PROGRAMDATA': 'C:\\ProgramData',
 'PROGRAMFILES': 'C:\\Program Files',
 'PSMODULEPATH': 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\',
 'PUBLIC': 'C:\\Users\\Public',
 'PYTHONIOENCODING': 'cp437',
 'QTJAVA': 'C:\\Program Files\\QuickTime\\QTSystem\\QTJava.zip',
 'SESSIONNAME': 'Console',
 'SYSTEMDRIVE': 'C:',
 'SYSTEMROOT': 'C:\\Windows',
 'TEMP': 'C:\\Users\\mike\\AppData\\Local\\Temp',
 'TMP': 'C:\\Users\\mike\\AppData\\Local\\Temp',
 'USERDOMAIN': 'mike-PC',
 'USERNAME': 'mike',
 'USERPROFILE': 'C:\\Users\\mike',
 'VBOX_INSTALL_PATH': 'C:\\Program Files\\Oracle\\VirtualBox\\',
 'VS90COMNTOOLS': 'C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\Tools\\',
 'WINDIR': 'C:\\Windows',
 'WINDOWS_TRACING_FLAGS': '3',
 'WINDOWS_TRACING_LOGFILE': 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log',
 'WINGDB_ACTIVE': '1',
 'WINGDB_PYTHON': 'c:\\python27\\python.exe',
 'WINGDB_SPAWNCOOKIE': 'rvlxwsGdD7SHYIJm'}
print(os.environ["TMP"])
'C:\\Users\\mike\\AppData\\Local\\Temp'

You could also use the os.getenv function to access this environmental variable:

os.getenv("TMP")
'C:\\Users\\mike\\AppData\\Local\\Temp'
os.environ["TMP2"]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    os.environ["TMP2"]
  File "C:\Python27\lib\os.py", line 423, in __getitem__
    return self.data[key.upper()]
KeyError: 'TMP2'

print(os.getenv("TMP2"))
None

os.chdir() and os.getcwd()

 os.getcwd()
'C:\\Python27'
os.chdir(r"c:\Users\mike\Documents")
os.getcwd()
'c:\\Users\\mike\\Documents'

os.mkdir() and os.makedirs()

>>> os.mkdir("test")
>>> path = r'C:\Users\mike\Documents\pytest'
>>> os.mkdir(path)
>>> path = r'C:\Users\mike\Documents\pytest\2014\02\19'
>>> os.makedirs(path)

os.remove() and os.rmdir()

The os.remove() and os.rmdir() functions are used for deleting files and directories respectively. Let’s look at an example of os.remove():

>>> os.remove("test.txt")

Now let’s look at an example of os.rmdir():

>>> os.rmdir("pytest")

os.rename(src, dst)

>>> os.rename("test.txt", "pytest.txt")

os.startfile()

>>> os.startfile(r'C:\Users\mike\Documents\labels.pdf')

os.walk()

>>> path = r'C:\Python27\Tools'
>>> for root, dirs, files in os.walk(path):
        print(root)

C:\Python27\Tools
C:\Python27\Tools\i18n
C:\Python27\Tools\pynche
C:\Python27\Tools\pynche\X
C:\Python27\Tools\Scripts
C:\Python27\Tools\versioncheck
C:\Python27\Tools\webchecker

If you want, you can also loop over dirs and files too. Here’s one way to do it:

>>> for root, dirs, files in os.walk(path):
        print(root)
        for _dir in dirs:
            print(_dir)
        for _file in files:
            print(_file)

os.path

os.path.basename

>>> os.path.basename(r'C:\Python27\Tools\pynche\ChipViewer.py')
'ChipViewer.py'

os.path.dirname

>>> os.path.dirname(r'C:\Python27\Tools\pynche\ChipViewer.py')
'C:\\Python27\\Tools\\pynche'

os.path.exists

>>> os.path.exists(r'C:\Python27\Tools\pynche\ChipViewer.py')
True
>>> os.path.exists(r'C:\Python27\Tools\pynche\fake.py')
False

os.path.isdir / os.path.isfile

>>> os.path.isfile(r'C:\Python27\Tools\pynche\ChipViewer.py')
True
>>> os.path.isdir(r'C:\Python27\Tools\pynche\ChipViewer.py')
False
>>> os.path.isdir(r'C:\Python27\Tools\pynche')
True
>>> os.path.isfile(r'C:\Python27\Tools\pynche')
False

os.path.join

>>> os.path.join(r'C:\Python27\Tools\pynche', 'ChipViewer.py')
'C:\\Python27\\Tools\\pynche\\ChipViewer.py'

os.path.split

The split method will split a path into a tuple that contains the directory and the file. Let’s take a look:

>>> os.path.split(r'C:\Python27\Tools\pynche\ChipViewer.py')
('C:\\Python27\\Tools\\pynche', 'ChipViewer.py')
 >>> os.path.split(r'C:\Python27\Tools\pynche')
('C:\\Python27\\Tools', 'pynche')
>>> dirname, fname = os.path.split(r'C:\Python27\Tools\pynche\ChipViewer.py')
>>> dirname
'C:\\Python27\\Tools\\pynche'
>>> fname
'ChipViewer.py'
automation modules of python

SMTPLIB Module

Email Basics – How to Send an Email with smtplib

import smtplib

HOST = "mySMTP.server.com"
SUBJECT = "Test email from Python"
TO = "[email protected]ss.org"
FROM = "[email protected]"
text = "Python 3.4 rules them all!"

BODY = "\r\n".join((
    "From: %s" % FROM,
    "To: %s" % TO,
    "Subject: %s" % SUBJECT ,
    "",
    text
    ))

server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY)
server.quit()
server.login(username, password)
import smtplib

def send_email(host, subject, to_addr, from_addr, body_text):
    """
    Send an email
    """
    BODY = "\r\n".join((
            "From: %s" % from_addr,
            "To: %s" % to_addr,
            "Subject: %s" % subject ,
            "",
            body_text
            ))
    server = smtplib.SMTP(host)
    server.sendmail(from_addr, [to_addr], BODY)
    server.quit()

if __name__ == "__main__":
    host = "mySMTP.server.com"
    subject = "Test email from Python"
    to_addr = "[email protected]"
    from_addr = "[email protected]"
    body_text = "Python rules them all!"
    send_email(host, subject, to_addr, from_addr, body_text)

Let’s take a look at the config file (save it as email.ini):

[smtp]
server = some.server.com
from_addr = [email protected]
import os
import smtplib
import sys

from configparser import ConfigParser

def send_email(subject, to_addr, body_text):
    """
    Send an email
    """
    base_path = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_path, "email.ini")

    if os.path.exists(config_path):
        cfg = ConfigParser()
        cfg.read(config_path)
    else:
        print("Config not found! Exiting!")
        sys.exit(1)

    host = cfg.get("smtp", "server")
    from_addr = cfg.get("smtp", "from_addr")

    BODY = "\r\n".join((
        "From: %s" % from_addr,
        "To: %s" % to_addr,
        "Subject: %s" % subject ,
        "",
        body_text
    ))
    server = smtplib.SMTP(host)
    server.sendmail(from_addr, [to_addr], BODY)
    server.quit()

if __name__ == "__main__":
    subject = "Test email from Python"
    to_addr = "[email protected]"
    body_text = "Python rules them all!"
    send_email(subject, to_addr, body_text)

Sending Multiple Emails at Once

import os
import smtplib
import sys

from configparser import ConfigParser

def send_email(subject, body_text, emails):
    """
    Send an email
    """
    base_path = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_path, "email.ini")

    if os.path.exists(config_path):
        cfg = ConfigParser()
        cfg.read(config_path)
    else:
        print("Config not found! Exiting!")
        sys.exit(1)

    host = cfg.get("smtp", "server")
    from_addr = cfg.get("smtp", "from_addr")

    BODY = "\r\n".join((
            "From: %s" % from_addr,
            "To: %s" % ', '.join(emails),
            "Subject: %s" % subject ,
            "",
            body_text
            ))
    server = smtplib.SMTP(host)
    server.sendmail(from_addr, emails, BODY)
    server.quit()

if __name__ == "__main__":
    emails = ["[email protected]", "[email protected]"]
    subject = "Test email from Python"
    body_text = "Python rules them all!"
    send_email(subject, body_text, emails)

Send email using the TO, CC and BCC lines

import os
import smtplib
import sys

from configparser import ConfigParser

def send_email(subject, body_text, to_emails, cc_emails, bcc_emails):
    """
    Send an email
    """
    base_path = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_path, "email.ini")

    if os.path.exists(config_path):
        cfg = ConfigParser()
        cfg.read(config_path)
    else:
        print("Config not found! Exiting!")
        sys.exit(1)

    host = cfg.get("smtp", "server")
    from_addr = cfg.get("smtp", "from_addr")

    BODY = "\r\n".join((
            "From: %s" % from_addr,
            "To: %s" % ', '.join(to_emails),
            "CC: %s" % ', '.join(cc_emails),
            "BCC: %s" % ', '.join(bcc_emails),
            "Subject: %s" % subject ,
            "",
            body_text
            ))
    emails = to_emails + cc_emails + bcc_emails

    server = smtplib.SMTP(host)
    server.sendmail(from_addr, emails, BODY)
    server.quit()

if __name__ == "__main__":
    emails = ["[email protected]"]
    cc_emails = ["[email protected]"]
    bcc_emails = ["[email protected]"]

    subject = "Test email from Python"
    body_text = "Python rules them all!"
    send_email(subject, body_text, emails, cc_emails, bcc_emails)

Add an attachment / body using the email module

import os
import smtplib
import sys

from configparser import ConfigParser
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.utils import formatdate

<em>#----------------------------------------------------------------------</em>
def send_email_with_attachment(subject, body_text, to_emails,
                               cc_emails, bcc_emails, file_to_attach):
    """
    Send an email with an attachment
    """
    base_path = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_path, "email.ini")
    header = 'Content-Disposition', 'attachment; filename="%s"' % file_to_attach

    <em># get the config</em>
    if os.path.exists(config_path):
        cfg = ConfigParser()
        cfg.read(config_path)
    else:
        print("Config not found! Exiting!")
        sys.exit(1)

    <em># extract server and from_addr from config</em>
    host = cfg.get("smtp", "server")
    from_addr = cfg.get("smtp", "from_addr")

    <em># create the message</em>
    msg = MIMEMultipart()
    msg["From"] = from_addr
    msg["Subject"] = subject
    msg["Date"] = formatdate(localtime=True)
    if body_text:
        msg.attach( MIMEText(body_text) )

    msg["To"] = ', '.join(to_emails)
    msg["cc"] = ', '.join(cc_emails)

    attachment = MIMEBase('application', "octet-stream")
    try:
        with open(file_to_attach, "rb") as fh:
            data = fh.read()
        attachment.set_payload( data )
        encoders.encode_base64(attachment)
        attachment.add_header(*header)
        msg.attach(attachment)
    except IOError:
        msg = "Error opening attachment file %s" % file_to_attach
        print(msg)
        sys.exit(1)

    emails = to_emails + cc_emails

    server = smtplib.SMTP(host)
    server.sendmail(from_addr, emails, msg.as_string())
    server.quit()

if __name__ == "__main__":
    emails = ["[email protected]", "[email protected]"]
    cc_emails = ["[email protected]"]
    bcc_emails = ["[email protected]"]

    subject = "Test email with attachment from Python"
    body_text = "This email contains an attachment!"
    path = "/path/to/some/file"
    send_email_with_attachment(subject, body_text, emails,
                               cc_emails, bcc_emails, path)

Make Youtube video Downloader with python

Leave a Comment