id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
2,900 | will return the most recent threads in your gmail account you can pass an optional maxresults keyword argument to change this limitrecentthreads ezgmail recent(len(recentthreads recentthreads ezgmail recent(maxresults= len(recentthreads searching mail from gmail account in addition to using ezgmail unread(and ezgmail recent()you can search for specific emailsthe same way you would if you entered queries into the resultthreads ezgmail search('robocop'len(resultthreads ezgmail summary(resultthreadsaljon do you want to watch robocop this weekenddec the previous search(call should yield the same results as if you had entered "robocopinto the search boxas in figure - figure - searching for "robocopemails at the gmail website like unread(and recent()the search(function returns list of gmailthread objects you can also pass any of the special search operators that you can enter into the search box to the search(functionsuch as the followingfor unread emails 'from:al@inventwithpython comfor emails from al@inventwithpython com 'subject:hellofor emails with "helloin the subject 'has:attachmentfor emails with file attachments 'label:unreadyou can view full list of search operators at /mail/answer/ ?hl=endownloading attachments from gmail account the gmailmessage objects have an attachments attribute that is list of filenames for the message' attached files you can pass any of these names to sending email and text messages |
2,901 | you can also download all of them at once with downloadallattachments(by defaultezgmail saves attachments to the current working directorybut you can pass an additional downloadfolder keyword argument to downloadattachment(and downloadallattachments(as well for exampleimport ezgmail threads ezgmail search('vacation photos'threads[ messages[ attachments ['tulips jpg''canal jpg''bicycles jpg'threads[ messages[ downloadattachment('tulips jpg'threads[ messages[ downloadallattachments(downloadfolder='vacat ion '['tulips jpg''canal jpg''bicycles jpg'if file already exists with the attachment' filenamethe downloaded attachment will automatically overwrite it ezgmail contains additional featuresand you can find the full documentation at smtp much as http is the protocol used by computers to send web pages across the internetsimple mail transfer protocol (smtpis the protocol used for sending email smtp dictates how email messages should be formattedencryptedand relayed between mail servers and all the other details that your computer handles after you click send you don' need to know these technical detailsthoughbecause python' smtplib module simplifies them into few functions smtp just deals with sending emails to others different protocolcalled imapdeals with retrieving emails sent to you and is described in "imapon page in addition to smtp and imapmost web-based email providers today have other security measures in place to protect against spamphishingand other malicious email usage these measures prevent python scripts from logging in to an email account with the smtplib and imapclient modules howevermany of these services have apis and specific python modules that allow scripts to access them this covers gmail' module for othersyou'll need to consult their online documentation sending email you may be familiar with sending emails from outlook or thunderbird or through website such as gmail or yahoo mail unfortunatelypython doesn' offer you nice graphical user interface like those services insteadyou call functions to perform each major step of smtpas shown in the following interactive shell example |
2,902 | don' enter this example in the interactive shellit won' workbecause smtp example combob@example commy_secret_passwordand alice@example com are just placeholders this code is just an overview of the process of sending email with python import smtplib smtpobj smtplib smtp('smtp example com' smtpobj ehlo(( 'mx example com at your service ]\nsize bitmime\nstarttls\nenhancedstatuscodes\nchunking'smtpobj starttls(( bready to start tls'smtpobj login('bob@example com''my_secret_password'( baccepted'smtpobj sendmail('bob@example com''alice@example com''subjectso long \ndear aliceso long and thanks for all the fish sincerelybob'{smtpobj quit(( bclosing connection ko sm pbd gsmtp'in the following sectionswe'll go through each stepreplacing the placeholders with your information to connect and log in to an smtp serversend an emailand disconnect from the server connecting to an smtp server if you've ever set up thunderbirdoutlookor another program to connect to your email accountyou may be familiar with configuring the smtp server and port these settings will be different for each email providerbut web search for smtp settings should turn up the server and port to use the domain name for the smtp server will usually be the name of your email provider' domain namewith smtp in front of it for exampleverizon' smtp server is at smtp verizon net table - lists some common email providers and their smtp servers (the port is an integer value and will almost always be it' used by the command encryption standardtls table - email providers and their smtp servers provider smtp server domain name gmailsmtp gmail com outlook com/hotmail comsmtp-mail outlook com yahoo mailsmtp mail yahoo com at& smpt mail att net (port comcast smtp comcast net verizon smtp verizon net (port *additional security measures prevent python from being able to log in to these servers with the smtplib module the ezgmail module can bypass this difficulty for gmail accounts sending email and text messages |
2,903 | providercreate an smtp object by calling smptlib smtp()passing the domain name as string argumentand passing the port as an integer argument the smtp object represents connection to an smtp mail server and has methods for sending emails for examplethe following call creates an smtp object for connecting to an imaginary email serversmtpobj smtplib smtp('smtp example com' type(smtpobjentering type(smtpobjshows you that there' an smtp object stored in smtpobj you'll need this smtp object in order to call the methods that log you in and send emails if the smptlib smtp(call is not successfulyour smtp server might not support tls on port in this caseyou will need to create an smtp object using smtplib smtp_ssl(and port instead smtpobj smtplib smtp_ssl('smtp example com' note if you are not connected to the internetpython will raise socket gaierror[errno getaddrinfo failed or similar exception for your programsthe differences between tls and ssl aren' important you only need to know which encryption standard your smtp server uses so you know how to connect to it in all of the interactive shell examples that followthe smtpobj variable will contain an smtp object returned by the smtplib smtp(or smtplib smtp_ssl(function sending the smtp "hellomessage once you have the smtp objectcall its oddly named ehlo(method to "say helloto the smtp email server this greeting is the first step in smtp and is important for establishing connection to the server you don' need to know the specifics of these protocols just be sure to call the ehlo(method first thing after getting the smtp object or else the later method calls will result in errors the following is an example of an ehlo(call and its return valuesmtpobj ehlo(( 'mx example com at your service ]\nsize bitmime\nstarttls\nenhancedstatuscodes\nchunking'if the first item in the returned tuple is the integer (the code for "successin smtp)then the greeting succeeded starting tls encryption if you are connecting to port on the smtp server (that isyou're using tls encryption)you'll need to call the starttls(method next this required |
2,904 | (using ssl)then encryption is already set upand you should skip this step here' an example of the starttls(method callsmtpobj starttls(( bready to start tls'the starttls(method puts your smtp connection in tls mode the in the return value tells you that the server is ready logging in to the smtp server once your encrypted connection to the smtp server is set upyou can log in with your username (usually your email addressand email password by calling the login(method smtpobj login('my_email_address@example com''my_secret_password'( baccepted'pass string of your email address as the first argument and string of your password as the second argument the in the return value means authentication was successful python raises an smtplib smtp authenticationerror exception for incorrect passwords warning be careful about putting passwords in your source code if anyone ever copies your programthey'll have access to your email accountit' good idea to call input(and have the user type in the password it may be inconvenient to have to enter password each time you run your programbut this approach prevents you from leaving your password in an unencrypted file on your computer where hacker or laptop thief could easily get it sending an email once you are logged in to your email provider' smtp serveryou can call the sendmail(method to actually send the email the sendmail(method call looks like thissmtpobj sendmail('my_email_address@example com''recipient@example com''subjectso long \ndear aliceso long and thanks for all the fish sincerelybob'{the sendmail(method requires three argumentsyour email address as string (for the email' "fromaddressthe recipient' email address as stringor list of strings for multiple recipients (for the "toaddressthe email body as string sending email and text messages |
2,905 | subject line of the email the '\nnewline character separates the subject line from the main body of the email the return value from sendmail(is dictionary there will be one keyvalue pair in the dictionary for each recipient for whom email delivery failed an empty dictionary means all recipients were successfully sent the email disconnecting from the smtp server be sure to call the quit(method when you are done sending emails this will disconnect your program from the smtp server smtpobj quit(( bclosing connection ko sm pbd gsmtp'the in the return value means the session is ending to review all the steps for connecting and logging in to the serversending emailand disconnectingsee "sending emailon page imap just as smtp is the protocol for sending emailthe internet message access protocol (imapspecifies how to communicate with an email provider' server to retrieve emails sent to your email address python comes with an imaplib modulebut in fact the third-party imapclient module is easier to use this provides an introduction to using imapclientthe full documentation is at the imapclient module downloads emails from an imap server in rather complicated format most likelyyou'll want to convert them from this format into simple string values the pyzmail module does the hard job of parsing these email messages for you you can find the complete documentation for pyzmail at install imapclient and pyzmail from terminal window with pip install --user - imapclient=and pip install --user - pyzmail =on windows (or using pip on macos and linuxappendix has steps on how to install third-party modules retrieving and deleting emails with imap finding and retrieving an email in python is multistep process that requires both the imapclient and pyzmail third-party modules just to give you an overviewhere' full example of logging in to an imap serversearching for emailsfetching themand then extracting the text of the email messages from them import imapclient imapobj imapclient imapclient('imap example com'ssl=trueimapobj login('my_email_address@example com''my_secret_password' |
2,906 | imapobj select_folder('inbox'readonly=trueuids imapobj search(['since -jul- ']uids [ rawmessages imapobj fetch([ ]['body[]''flags']import pyzmail message pyzmail pyzmessage factory(rawmessages[ ][ 'body[]']message get_subject('hello!message get_addresses('from'[('edward snowden''esnowden@nsa gov')message get_addresses('to'[('jane doe''jdoe@example com')message get_addresses('cc'[message get_addresses('bcc'[message text_part !none true message text_part get_payload(decode(message text_part charset'follow the money \ \ \ \ -ed\ \nmessage html_part !none true message html_part get_payload(decode(message html_part charset'so longand thanks for all the fish!al\ \nimapobj logout(you don' have to memorize these steps after we go through each step in detailyou can come back to this overview to refresh your memory connecting to an imap server just like you needed an smtp object to connect to an smtp server and send emailyou need an imapclient object to connect to an imap server and receive email first you'll need the domain name of your email provider' imap server this will be different from the smtp server' domain name table - lists the imap servers for several popular email providers table - email providers and their imap servers provider imap server domain name gmailimap gmail com outlook com/hotmail comimap-mail outlook com yahoo mailimap mail yahoo com at& imap mail att net comcast imap comcast net verizon incoming verizon net *additional security measures prevent python from being able to log in to these servers with the imapclient module sending email and text messages |
2,907 | imapclient(function to create an imapclient object most email providers require ssl encryptionso pass the ssl=true keyword argument enter the following into the interactive shell (using your provider' domain name)import imapclient imapobj imapclient imapclient('imap example com'ssl=truein all of the interactive shell examples in the following sectionsthe imapobj variable contains an imapclient object returned from the imapclient imapclient(function in this contexta client is the object that connects to the server logging in to the imap server once you have an imapclient objectcall its login(methodpassing in the username (this is usually your email addressand password as strings imapobj login('my_email_address@example com''my_secret_password''my_email_address@example com jane doe authenticated (success)warning remember to never write password directly into your codeinsteaddesign your program to accept the password returned from input(if the imap server rejects this username/password combinationpython raises an imaplib error exception searching for email once you're logged onactually retrieving an email that you're interested in is two-step process firstyou must select folder you want to search through thenyou must call the imapclient object' search(methodpassing in string of imap search keywords selecting folder almost every account has an inbox folder by defaultbut you can also get list of folders by calling the imapclient object' list_folders(method this returns list of tuples each tuple contains information about single folder continue the interactive shell example by entering the followingimport pprint pprint pprint(imapobj list_folders()[(('\\hasnochildren',)'/''drafts') |
2,908 | (('\\hasnochildren',)'/''inbox')(('\\hasnochildren',)'/''sent')--snip-(('\\hasnochildren''\\flagged')'/''starred')(('\\hasnochildren''\\trash')'/''trash')the three values in each of the tuples--for example(('\hasnochildren',)'/''inbox')--are as followsa tuple of the folder' flags (exactly what these flags represent is beyond the scope of this bookand you can safely ignore this field the delimiter used in the name string to separate parent folders and subfolders the full name of the folder to select folder to search throughpass the folder' name as string into the imapclient object' select_folder(method imapobj select_folder('inbox'readonly=trueyou can ignore select_folder()' return value if the selected folder does not existpython raises an imaplib error exception the readonly=true keyword argument prevents you from accidentally making changes or deletions to any of the emails in this folder during the subsequent method calls unless you want to delete emailsit' good idea to always set readonly to true performing the search with folder selectedyou can now search for emails with the imapclient object' search(method the argument to search(is list of stringseach formatted to the imap' search keys table - describes the various search keys note that some imap servers may have slightly different implementations for how they handle their flags and search keys it may require some experimentation in the interactive shell to see exactly how they behave you can pass multiple imap search key strings in the list argument to the search(method the messages returned are the ones that match all the search keys if you want to match any of the search keysuse the or search key for the not and or search keysone and two complete search keys follow the not and orrespectively sending email and text messages |
2,909 | search key meaning 'allreturns all messages in the folder you may run into imaplib size limits if you request all the messages in large folder see "size limitson page 'before date''on date''since datethese three search keys returnrespectivelymessages that were received by the imap server beforeonor after the given date the date must be formatted like -jul- alsowhile 'since -jul- will match messages on and after july 'before -jul- will match only messages before july but not on july itself 'subject string''body string''text stringreturns messages where string is found in the subjectbodyor eitherrespectively if string has spaces in itthen enclose it with double quotes'text "search with spaces"'from string''to string''cc string''bcc stringreturns all messages where string is found in the "fromemail address"toaddresses"cc(carbon copyaddressesor "bcc(blind carbon copyaddressesrespectively if there are multiple email addresses in stringthen separate them with spaces and enclose them all with double quotes'cc "firstccexample com secondcc@example com"'seen''unseenreturns all messages with and without the \seen flagrespectively an email obtains the \seen flag if it has been accessed with fetch(method call (described lateror if it is clicked when you're checking your email in an email program or web browser it' more common to say the email has been "readrather than "seen,but they mean the same thing 'answered''unansweredreturns all messages with and without the \answered flagrespectively message obtains the \answered flag when it is replied to 'deleted''undeletedreturns all messages with and without the \deleted flagrespectively email messages deleted with the delete_messages(method are given the \deleted flag but are not permanently deleted until the expunge(method is called (see "deleting emailson page note that some email providers automatically expunge emails 'draft''undraftreturns all messages with and without the \draft flagrespectively draft messages are usually kept in separate drafts folder rather than in the inbox folder 'flagged''unflaggedreturns all messages with and without the \flagged flagrespectively this flag is usually used to mark email messages as "importantor "urgent 'larger ''smaller nreturns all messages larger or smaller than bytesrespectively 'not search-keyreturns the messages that search-key would not have returned 'or search-key search-key returns the messages that match either the first or second search-key |
2,910 | imapobj search(['all']returns every message in the currently selected folder imapobj search(['on -jul- ']returns every message sent on july imapobj search(['since -jan- ''before -feb- ''unseen']returns every message sent in january that is unread (note that this means on and after january and up to but not including february returns every message from alice@example com sent since the start of imapobj search(['since -jan- ''from alice@example com']imapobj search(['since -jan- ''not from alice@example com']returns every message sent from everyone except alice@example com since the start of imapobj search(['or from alice@example com from bob@example com']returns every message ever sent from alice@example com or bob@example com imapobj search(['from alice@example com''from bob@example com']trick examplethis search never returns any messagesbecause messages must match all search keywords since there can be only one "fromaddressit is impossible for message to be from both alice@example com and bob@example com the search(method doesn' return the emails themselves but rather unique ids (uidsfor the emailsas integer values you can then pass these uids to the fetch(method to obtain the email content continue the interactive shell example by entering the followinguids imapobj search(['since -jul- ']uids [ herethe list of message ids (for messages received july onwardreturned by search(is stored in uids the list of uids returned on your computer will be different from the ones shown herethey are unique to particular email account when you later pass uids to other function callsuse the uid values you receivednot the ones printed in this book' examples size limits if your search matches large number of email messagespython might raise an exception that says imaplib errorgot more than bytes when this happensyou will have to disconnect and reconnect to the imap server and try again sending email and text messages |
2,911 | too much memory unfortunatelythe default size limit is often too small you can change this limit from , bytes to , , bytes by running this codeimport imaplib imaplib _maxline this should prevent this error message from coming up again you may want to make these two lines part of every imap program you write fetching an email and marking it as read once you have list of uidsyou can call the imapclient object' fetch(method to get the actual email content the list of uids will be fetch()' first argument the second argument should be the list ['body[]']which tells fetch(to download all the body content for the emails specified in your uid list let' continue our interactive shell example rawmessages imapobj fetch(uids['body[]']import pprint pprint pprint(rawmessages{ {'body[]''delivered-tomy_email_address@example com\ \ 'receivedby with smtp id --snip-'\ \ '=_part_ --\ \ ''seq' }import pprint and pass the return value from fetch()stored in the variable rawmessagesto pprint pprint(to "pretty printitand you'll see that this return value is nested dictionary of messages with uids as the keys each message is stored as dictionary with two keys'body[]and 'seqthe 'body[]key maps to the actual body of the email the 'seqkey is for sequence numberwhich has similar role to the uid you can safely ignore it as you can seethe message content in the 'body[]key is pretty unintelligible it' in format called rfc which is designed for imap servers to read but you don' need to understand the rfc formatlater in this the pyzmail module will make sense of it for you when you selected folder to search throughyou called select_folder(with the readonly=true keyword argument doing this prevents you from accidentally deleting an email--but it also means that emails will not get marked as read if you fetch them with the fetch(method if you do want emails to be marked as read when you fetch themyou'll need to pass readonly=false to select_folder(if the selected folder is already in read-only modeyou can reselect the current folder with another call to select_folder()this time with the readonly=false keyword argumentimapobj select_folder('inbox'readonly=false |
2,912 | the raw messages returned from the fetch(method still aren' very useful to people who just want to read their email the pyzmail module parses these raw messages and returns them as pyzmessage objectswhich make the subjectbody"tofield"fromfieldand other sections of the email easily accessible to your python code continue the interactive shell example with the following (using uids from your own email accountnot the ones shown here)import pyzmail message pyzmail pyzmessage factory(rawmessages[ ][ 'body[]']firstimport pyzmail thento create pyzmessage object of an emailcall the pyzmail pyzmessage factory(function and pass it the 'body[]section of the raw message (note that the prefix means this is bytes valuenot string value the difference isn' too importantjust remember to include the prefix in your code store the result in message now message contains pyzmessage objectwhich has several methods that make it easy to get the email' subject lineas well as all sender and recipient addresses the get_subject(method returns the subject as simple string value the get_addresses(method returns list of addresses for the field you pass it for examplethe method calls might look like thismessage get_subject('hello!message get_addresses('from'[('edward snowden''esnowden@nsa gov')message get_addresses('to'[('jane doe''my_email_address@example com')message get_addresses('cc'[message get_addresses('bcc'[notice that the argument for get_addresses(is 'from''to''cc'or 'bccthe return value of get_addresses(is list of tuples each tuple contains two stringsthe first is the name associated with the email addressand the second is the email address itself if there are no addresses in the requested fieldget_addresses(returns blank list herethe 'cccarbon copy and 'bccblind carbon copy fields both contained no addresses and so returned empty lists getting the body from raw message emails can be sent as plaintexthtmlor both plaintext emails contain only textwhile html emails can have colorsfontsimagesand other features that make the email message look like small web page if an email is only plaintextits pyzmessage object will have its html_part attributes set to none likewiseif an email is only htmlits pyzmessage object will have its text_part attribute set to none sending email and text messages |
2,913 | method that returns the email' body as value of the bytes data type (the bytes data type is beyond the scope of this book but this still isn' string value that we can use ughthe last step is to call the decode(method on the bytes value returned by get_payload(the decode(method takes one argumentthe message' character encodingstored in the text_part charset or html_part charset attribute thisfinallywill return the string of the email' body continue the interactive shell example by entering the followingu message text_part !none true message text_part get_payload(decode(message text_part charsetv 'so longand thanks for all the fish!\ \ \ \ -al\ \nw message html_part !none true message html_part get_payload(decode(message html_part charset'so longand thanks for all the fish!-al \ \nthe email we're working with has both plaintext and html contentso the pyzmessage object stored in message has text_part and html_part attributes not equal to none calling get_payload(on the message' text_part and then calling decode(on the bytes value returns string of the text version of the email using get_payload(and decode(with the message' html_part returns string of the html version of the email deleting emails to delete emailspass list of message uids to the imapclient object' delete_messages(method this marks the emails with the \deleted flag calling the expunge(method permanently deletes all emails with the /deleted flag in the currently selected folder consider the following interactive shell exampleu imapobj select_folder('inbox'readonly=falsev uids imapobj search(['on -jul- ']uids [ imapobj delete_messages(uidsw { ('\\seen''\\deleted')imapobj expunge(('success'[( 'exists')]here we select the inbox by calling select_folder(on the imapclient object and passing 'inboxas the first argumentwe also pass the keyword argument readonly=false so that we can delete emails we search the inbox for messages received on specific date and store the returned message ids in uids calling delete_message(and passing it uids returns dictionaryeach key-value pair is message id and tuple of the message' |
2,914 | if there were no problems expunging the emails note that some email providers automatically expunge emails deleted with delete_messages(instead of waiting for an expunge command from the imap client disconnecting from the imap server when your program has finished retrieving or deleting emailssimply call the imapclient' logout(method to disconnect from the imap server imapobj logout(if your program runs for several minutes or morethe imap server may time outor automatically disconnect in this casethe next method call your program makes on the imapclient object should raise an exception like the followingimaplib abortsocket error[winerror an existing connection was forcibly closed by the remote host in this eventyour program will have to call imapclient imapclient(to connect again whewthat' it there were lot of hoops to jump throughbut you now have way to get your python programs to log in to an email account and fetch emails you can always consult the overview in "retrieving and deleting emails with imapon page whenever you need to remember all of the steps projectsending member dues reminder emails say you have been "volunteeredto track member dues for the mandatory volunteerism club this is truly boring jobinvolving maintaining spreadsheet of everyone who has paid each month and emailing reminders to those who haven' instead of going through the spreadsheet yourself and copying and pasting the same email to everyone who is behind on dueslet' --you guessed it--write script that does this for you at high levelhere' what your program will do read data from an excel spreadsheet find all members who have not paid dues for the latest month find their email addresses and send them personalized reminders this means your code will need to do the following open and read the cells of an excel document with the openpyxl module (see for working with excel files create dictionary of members who are behind on their dues sending email and text messages |
2,915 | log in to an smtp server by calling smtplib smtp()ehlo()starttls()and login(for all members behind on their duessend personalized reminder email by calling the sendmail(method open new file editor tab and save it as sendduesreminders py step open the excel file let' say the excel spreadsheet you use to track membership dues payments looks like figure - and is in file named duesrecords xlsx you can download this file from figure - the spreadsheet for tracking member dues payments this spreadsheet has every member' name and email address each month has column tracking memberspayment statuses the cell for each member is marked with the text paid once they have paid their dues the program will have to open duesrecords xlsx and figure out the column for the latest month by reading the sheet max_column attribute (you can consult for more information on accessing cells in excel spreadsheet files with the openpyxl module enter the following code into the file editor tab#python sendduesreminders py sends emails based on payment status in spreadsheet import openpyxlsmtplibsys open the spreadsheet and get the latest dues status wb openpyxl load_workbook('duesrecords xlsx' sheet wb get_sheet_by_name('sheet ' |
2,916 | latestmonth sheet cell(row= column=lastcolvalue todocheck each member' payment status todolog in to email account todosend out reminder emails after importing the openpyxlsmtpliband sys moduleswe open our duesrecords xlsx file and store the resulting workbook object in wb then we get sheet and store the resulting worksheet object in sheet now that we have worksheet objectwe can access rowscolumnsand cells we store the highest column in lastcol wand we then use row number and lastcol to access the cell that should hold the most recent month we get the value in this cell and store it in latestmonth step find all unpaid members once you've determined the column number of the latest month (stored in lastcol)you can loop through all rows after the first row (which has the column headersto see which members have the text paid in the cell for that month' dues if the member hasn' paidyou can grab the member' name and email address from columns and respectively this information will go into the unpaidmembers dictionarywhich will track all members who haven' paid in the most recent month add the following code to sendduesreminder py #python sendduesreminders py sends emails based on payment status in spreadsheet --snip-check each member' payment status unpaidmembers { for in range( sheet max_row ) payment sheet cell(row=rcolumn=lastcolvalue if payment !'paid' name sheet cell(row=rcolumn= value email sheet cell(row=rcolumn= value unpaidmembers[nameemail this code sets up an empty dictionary unpaidmembers and then loops through all the rows after the first for each rowthe value in the most recent column is stored in payment if payment is not equal to 'paid'then the value of the first column is stored in name wthe value of the second column is stored in email xand name and email are added to unpaidmembers sending email and text messages |
2,917 | once you have list of all unpaid membersit' time to send them email reminders add the following code to your programexcept with your real email address and provider information#python sendduesreminders py sends emails based on payment status in spreadsheet --snip-log in to email account smtpobj smtplib smtp('smtp example com' smtpobj ehlo(smtpobj starttls(smtpobj login('my_email_address@example com'sys argv[ ]create an smtp object by calling smtplib smtp(and passing it the domain name and port for your provider call ehlo(and starttls()and then call login(and pass it your email address and sys argv[ ]which will store your password string you'll enter the password as command line argument each time you run the programto avoid saving your password in your source code once your program has logged in to your email accountit should go through the unpaidmembers dictionary and send personalized email to each member' email address add the following to sendduesreminders py#python sendduesreminders py sends emails based on payment status in spreadsheet --snip-send out reminder emails for nameemail in unpaidmembers items() body "subject% dues unpaid \ndear % ,\nrecords show that you have not paid dues for % please make this payment as soon as possible thank you!'(latestmonthnamelatestmonthv print('sending email to % emailw sendmailstatus smtpobj sendmail('my_email_address@example com'emailbodyx if sendmailstatus !{}print('there was problem sending email to % % (emailsendmailstatus)smtpobj quit(this code loops through the names and emails in unpaidmembers for each member who hasn' paidwe customize message with the latest month and the member' nameand store the message in body we print output saying that we're sending an email to this member' email address then we call sendmail()passing it the from address and the customized message we store the return value in sendmailstatus |
2,918 | value if the smtp server reported an error sending that particular email the last part of the for loop at checks if the returned dictionary is nonempty andif it isprints the recipient' email address and the returned dictionary after the program is done sending all the emailsthe quit(method is called to disconnect from the smtp server when you run the programthe output will look something like thissending email to alice@example com sending email to bob@example com sending email to eve@example com the recipients will receive an email about their missed payments that looks just like an email you would have sent manually sending text messages with sms email gateways people are more likely to be near their smartphones than their computersso text messages are often more immediate and reliable way of sending notifications than email alsotext messages are usually shortermaking it more likely that person will get around to reading them the easiestthough not most reliableway to send text messages is by using an sms (short message serviceemail gatewayan email server that cell phone provider set up to receive text via email and then forward to the recipient as text message you can write program to send these emails using the ezgmail or smtplib modules the phone number and phone company' email server make up the recipient email address the subject and body of the email will be the body of the text message for exampleto send text to the phone number which is owned by verizon customeryou would send an email to @vtext com you can find the sms email gateway for cell phone provider by doing web search for "sms email gateway provider name,but table - lists the gateways for several popular providers many providers have separate email servers for sms which limits messages to charactersand mms (multimedia messaging service)which has no character limit if you wanted to send photoyou would have to use the mms gateway and attach the file to the email if you don' know the recipient' cell phone provideryou can try using carrier lookup sitewhich should provide phone number' carrier the best way to find these sites is by searching the web for "find cell phone provider for number many of these sites will let you look up numbers for free (though will charge you if you need to look up hundreds or thousands of phone numbers through their apisending email and text messages |
2,919 | cell phone provider sms gateway mms gateway at& number@txt att net number@mms att net boost mobile number@sms myboostmobile com same as sms cricket number@sms cricketwireless net number@mms cricketwireless net google fi number@msg fi google com same as sms metro pcs number@mymetropcs com same as sms republic wireless number@text republicwireless com same as sms sprint number@messaging sprintpcs com number@pm sprint com -mobile number@tmomail net same as sms cellular number@email uscc net number@mms uscc net verizon number@vtext com number@vzwpix com virgin mobile number@vmobl com number@vmpix com xfinity mobile number@vtext com number@mypixmessages com while sms email gateways are free and simple to usethere are several major disadvantages to themyou have no guarantee that the text will arrive promptlyor at all you have no way of knowing if the text failed to arrive the text recipient has no way of replying sms gateways may block you if you send too many emailsand there' no way to find out how many is "too many just because the sms gateway delivers text message today doesn' mean it will work tomorrow sending texts via an sms gateway is ideal when you need to send the occasionalnonurgent message if you need more reliable serviceuse non-email sms gateway serviceas described next sending text messages with twilio in this sectionyou'll learn how to sign up for the free twilio service and use its python module to send text messages twilio is an sms gateway servicewhich means it allows you to send text messages from your programs via the internet although the free trial account comes with limited amount of credit and the texts will be prefixed with the words sent from twilio trial accountthis trial service is probably adequate for your personal programs but twilio isn' the only sms gateway service if you prefer not to use twilioyou can find alternative services by searching online for "free sms"gateway,"python sms api,or even "twilio alternatives |
2,920 | pip install --user --upgrade twilio on windows (or use pip on macos and linuxappendix has more details about installing third-party modules note this section is specific to the united states twilio does offer sms texting services for countries other than the united statessee the twilio module and its functions will work the same outside the united states signing up for twilio account go to up for new accountyou'll need to verify mobile phone number that you want to send texts to go to the verified caller ids page and add phone number you have access to twilio will text code to this number that you must enter to verify the number (this verification is necessary to prevent people from using the service to spam random phone numbers with text messages you will now be able to send texts to this phone number using the twilio module twilio provides your trial account with phone number to use as the sender of text messages you will need two more pieces of informationyour account sid and the auth (authenticationtoken you can find this information on the dashboard page when you are logged in to your twilio account these values act as your twilio username and password when logging in from python program sending text messages once you've installed the twilio modulesigned up for twilio accountverified your phone numberregistered twilio phone numberand obtained your account sid and auth tokenyou will finally be ready to send yourself text messages from your python scripts compared to all the registration stepsthe actual python code is fairly simple with your computer connected to the internetenter the following into the interactive shellreplacing the accountsidauthtokenmytwilionumberand mycellphone variable values with your real informationu from twilio rest import client accountsid 'acxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxauthtoken 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxv twiliocli client(accountsidauthtokenmytwilionumber '+ mycellphone '+ message twiliocli messages create(body='mr watson come here want to see you 'from_=mytwilionumberto=mycellphonea few moments after typing the last lineyou should receive text message that readssent from your twilio trial account mr watson come here want to see you sending email and text messages |
2,921 | using from twilio rest import clientnot just import twilio store your account sid in accountsid and your auth token in authtoken and then call client(and pass it accountsid and authtoken the call to client(returns client object this object has messages attributewhich in turn has create(method you can use to send text messages this is the method that will instruct twilio' servers to send your text message after storing your twilio number and cell phone number in mytwilionumber and mycellphonerespectivelycall create(and pass it keyword arguments specifying the body of the text messagethe sender' number (mytwilionumber)and the recipient' number (mycellphonew the message object returned from the create(method will have information about the text message that was sent continue the interactive shell example by entering the followingmessage to '+ message from_ '+ message body 'mr watson come here want to see you the tofrom_and body attributes should hold your cell phone numbertwilio numberand messagerespectively note that the sending phone number is in the from_ attribute--with an underscore at the end--not from this is because from is keyword in python (you've seen it used in the from modulename import form of import statementfor example)so it cannot be used as an attribute name continue the interactive shell example with the followingmessage status 'queuedmessage date_created datetime datetime( message date_sent =none true the status attribute should give you string the date_created and date_sent attributes should give you datetime object if the message has been created and sent it may seem odd that the status attribute is set to 'queuedand the date_sent attribute is set to none when you've already received the text message this is because you captured the message object in the message variable before the text was actually sent you will need to refetch the message object in order to see its most up-to-date status and date_sent every twilio message has unique string id (sidthat can be used to fetch the latest update of the message object continue the inter active shell example by entering the followingmessage sid 'sm de ba af fcb |
2,922 | updatedmessage status 'deliveredupdatedmessage date_sent datetime datetime( entering message sid shows you this message' long sid by passing this sid to the twilio client' get(method uyou can retrieve new message object with the most up-to-date information in this new message objectthe status and date_sent attributes are correct the status attribute will be set to one of the following string values'queued''sending''sent''delivered''undelivered'or 'failedthese statuses are self-explanatorybut for more precise detailstake look at the resources at rece ing te me ss age ith py thon unfortunatelyreceiving text messages with twilio is bit more complicated than sending them twilio requires that you have website running its own web application that' beyond the scope of these pagesbut you can find more details in this book' online resources (project"just text memodule the person you'll most often text from your programs is probably you texting is great way to send yourself notifications when you're away from your computer if you've automated boring task with program that takes couple of hours to runyou could have it notify you with text when it' finished or you may have regularly scheduled program running that sometimes needs to contact yousuch as weather-checking program that texts you reminder to pack an umbrella as simple examplehere' small python program with textmyself(function that sends message passed to it as string argument open new file editor tab and enter the following codereplacing the account sidauth tokenand phone numbers with your own information save it as textmyself py #python textmyself py defines the textmyself(function that texts message passed to it as string preset valuesaccountsid 'acxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxauthtoken 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxmynumber '+ twilionumber '+ sending email and text messages |
2,923 | def textmyself(message) twiliocli client(accountsidauthtokenw twiliocli messages create(body=messagefrom_=twilionumberto=mynumberthis program stores an account sidauth tokensending numberand receiving number it then defined textmyself(to take on argument umake client object vand call create(with the message you passed if you want to make the textmyself(function available to your other programssimply place the textmyself py file in the same folder as your python script whenever you want one of your programs to text youjust add the followingimport textmyself textmyself textmyself('the boring task is finished 'you need to sign up for twilio and write the texting code only once after thatit' just two lines of code to send text from any of your other programs summary we communicate with each other on the internet and over cell phone networks in dozens of different waysbut email and texting predominate your programs can communicate through these channelswhich gives them powerful new notification features you can even write programs running on different computers that communicate with one another directly via emailwith one program sending emails with smtp and the other retrieving them with imap python' smtplib provides functions for using the smtp to send emails through your email provider' smtp server likewisethe third-party imapclient and pyzmail modules let you access imap servers and retrieve emails sent to you although imap is bit more involved than smtpit' also quite powerful and allows you to search for particular emailsdownload themand parse them to extract the subject and body as string values as security and spam precautionsome popular email services like gmail don' allow you to use the standard smtp and imap protocols to access their services the ezgmail module acts as convenient wrapper for the gmail apiletting your python scripts access your gmail account highly recommend that you set up separate gmail account for your scripts to use so that potential bugs in your program don' cause problems for your personal gmail account texting is bit different from emailsinceunlike emailmore than just an internet connection is needed to send sms texts fortunatelyservices such as twilio provide modules to allow you to send text messages from your programs once you go through an initial setup processyou'll be able to send texts with just couple lines of code with these modules in your skill setyou'll be able to program the specific conditions under which your programs should send notifications or |
2,924 | they're running onpractice questions what is the protocol for sending emailfor checking and receiving emailwhat four smtplib functions/methods must you call to log in to an smtp server what two imapclient functions/methods must you call to log in to an imap server what kind of argument do you pass to imapobj search() what do you do if your code gets an error message that says got more than bytes the imapclient module handles connecting to an imap server and finding emails what is one module that handles reading the emails that imapclient collects when using the gmail apiwhat are the credentials json and token json files in the gmail apiwhat' the difference between "threadand "messageobjects using ezgmail search()how can you find emails that have file attachments what three pieces of information do you need from twilio before you can send text messagespractice projects for practicewrite programs that do the following random chore assignment emailer write program that takes list of people' email addresses and list of chores that need to be done and randomly assigns chores to people email each person their assigned chores if you're feeling ambitiouskeep record of each person' previously assigned chores so that you can make sure the program avoids assigning anyone the same chore they did last time for another possible featureschedule the program to run once week automatically here' hintif you pass list to the random choice(functionit will return randomly selected item from the list part of your code could look like thischores ['dishes''bathroom''vacuum''walk dog'randomchore random choice(choreschores remove(randomchorethis chore is now takenso remove it sending email and text messages |
2,925 | showed you how to use the requests module to scrape data from the morning and checks whether it' raining that day if sohave the program text you reminder to pack an umbrella before leaving the house auto unsubscriber write program that scans through your email accountfinds all the unsubscribe links in all your emailsand automatically opens them in browser this program will have to log in to your email provider' imap server and download all of your emails you can use beautiful soup (covered in to check for any instance where the word unsubscribe occurs within an html link tag once you have list of these urlsyou can use webbrowser open(to automatically open all of these links in browser you'll still have to manually go through and complete any additional steps to unsubscribe yourself from these lists in most casesthis involves clicking link to confirm but this script saves you from having to go through all of your emails looking for unsubscribe links you can then pass this script along to your friends so they can run it on their email accounts (just make sure your email password isn' hardcoded in the source code!controlling your computer through email write program that checks an email account every minutes for any instructions you email it and executes those instructions automatically for examplebittorrent is peer-to-peer downloading system using free bittorrent software such as qbittorrentyou can download large media files on your home computer if you email the program (completely legalnot at all piraticalbittorrent linkthe program will eventually check its emailfind this messageextract the linkand then launch qbittorrent to start downloading the file this wayyou can have your home computer begin downloads while you're awayand the (completely legalnot at all piraticaldownload can be finished by the time you return home covers how to launch programs on your computer using the subprocess popen(function for examplethe following call would launch the qbittorrent programalong with torrent fileqbprocess subprocess popen([' :\\program files ( )\\qbittorrent\qbittorrent exe''shakespeare_complete_works torrent']of courseyou'll want the program to make sure the emails come from you in particularyou might want to require that the emails contain passwordsince it is fairly trivial for hackers to fake "fromaddress in emails the program should delete the emails it finds so that it doesn' repeat instructions every time it checks the email account as an extra feature |
2,926 | command since you won' be sitting in front of the computer that is running the programit' good idea to use the logging functions (see to write text file log that you can check if errors come up qbittorrent (as well as other bittorrent applicationshas feature where it can quit automatically after the download completes explains how you can determine when launched application has quit with the wait(method for popen objects the wait(method call will block until qbittorrent has stoppedand then your program can email or text you notification that the download has completed there are lot of possible features you could add to this project if you get stuckyou can download an example implementation of this program from sending email and text messages |
2,927 | nipul at ing im age if you have digital camera or even if you just upload photos from your phone to facebookyou probably cross paths with digital image files all the time you may know how to use basic graphics softwaresuch as microsoft paint or paintbrushor even more advanced applications such as adobe photoshop but if you need to edit massive number of imagesediting them by hand can be lengthyboring job enter python pillow is third-party python module for interacting with image files the module has several functions that make it easy to cropresizeand edit the content of an image with the power to manipulate images the same way you would with software such as microsoft paint or adobe photoshoppython can automatically edit hundreds or thousands of images with ease you can install pillow by running pip install --user - pillow=appendix has more details on installing modules |
2,928 | in order to manipulate an imageyou need to understand the basics of how computers deal with colors and coordinates in images and how you can work with colors and coordinates in pillow but before you continueinstall the pillow module see appendix for help installing third-party modules colors and rgba values computer programs often represent color in an image as an rgba value an rgba value is group of numbers that specify the amount of redgreenblueand alpha (or transparencyin color each of these component values is an integer from (none at allto (the maximumthese rgba values are assigned to individual pixelsa pixel is the smallest dot of single color the computer screen can show (as you can imaginethere are millions of pixels on screena pixel' rgb setting tells it precisely what shade of color it should display images also have an alpha value to create rgba values if an image is displayed on the screen over background image or desktop wallpaperthe alpha value determines how much of the background you can "see throughthe image' pixel in pillowrgba values are represented by tuple of four integer values for examplethe color red is represented by ( this color has the maximum amount of redno green or blueand the maximum alpha valuemeaning it is fully opaque green is represented by ( )and blue is ( whitethe combination of all colorsis ( )while blackwhich has no color at allis ( if color has an alpha value of it is invisibleand it doesn' really matter what the rgb values are after allinvisible red looks the same as invisible black pillow uses the standard color names that html uses table - lists selection of standard color names and their values table - standard color names and their rgba values name rgba value name rgba value white ( red ( green ( blue ( gray ( yellow ( black ( purple ( pillow offers the imagecolor getcolor(function so you don' have to memorize rgba values for the colors you want to use this function takes color name string as its first argumentand the string 'rgbaas its second argumentand it returns an rgba tuple |
2,929 | interactive shellu from pil import imagecolor imagecolor getcolor('red''rgba'( imagecolor getcolor('red''rgba'( imagecolor getcolor('black''rgba'( imagecolor getcolor('chocolate''rgba'( imagecolor getcolor('cornflowerblue''rgba'( firstyou need to import the imagecolor module from pil (not from pillowyou'll see why in momentthe color name string you pass to imagecolor getcolor(is case-insensitiveso passing 'redv and passing 'redw give you the same rgba tuple you can also pass more unusual color nameslike 'chocolateand 'cornflower bluepillow supports huge number of color namesfrom 'aliceblueto 'whitesmokeyou can find the full list of more than standard color names in the resources at coordinates and box tuples image pixels are addressed with xand -coordinateswhich respectively specify pixel' horizontal and vertical locations in an image the origin is the pixel at the top-left corner of the image and is specified with the notation ( the first zero represents the -coordinatewhich starts at zero at the origin and increases going from left to right the second zero represents the -coordinatewhich starts at zero at the origin and increases going down the image this bears repeatingy-coordinates increase going downwardwhich is the opposite of how you may remember -coordinates being used in math class figure - demonstrates how this coordinate system works increases increases ( , ( , figure - the xand -coordinates of image of some sort of ancient data storage device manipulating images |
2,930 | means pillow is expecting tuple of four integer coordinates that represent rectangular region in an image the four integers arein orderas followsleft the -coordinate of the leftmost edge of the box top the -coordinate of the top edge of the box right the -coordinate of one pixel to the right of the rightmost edge of the box this integer must be greater than the left integer bottom the -coordinate of one pixel lower than the bottom edge of the box this integer must be greater than the top integer note that the box includes the left and top coordinates and goes up to but does not include the right and bottom coordinates for examplethe box tuple ( represents all the pixels in the black box in figure - figure - the area represented by the box tuple ( manipulating images with pillow now that you know how colors and coordinates work in pillowlet' use pillow to manipulate an image figure - is the image that will be used for all the interactive shell examples in this you can download it from once you have the image file zophie png in your current working directoryyou'll be ready to load the image of zophie into pythonlike sofrom pil import image catim image open('zophie png'to load the imageimport the image module from pillow and call image open()passing it the image' filename you can then store the loaded image in variable like catim pillow' module name is pil to make it backward compatible with an older module called python imaging librarythis is why you must run from pil import image instead of from pillow import image because of the way pillow' creators set up the pillow moduleyou must use the import statement from pil import imagerather than simply import pil |
2,931 | adds pounds (which is lot for catif the image file isn' in the current working directorychange the working directory to the folder that contains the image file by calling the os chdir(function import os os chdir(' :\\folder_with_image_file'the image open(function returns value of the image object data typewhich is how pillow represents an image as python value you can load an image object from an image file (of any formatby passing the image open(function string of the filename any changes you make to the image object can be saved to an image file (also of any formatwith the save(method all the rotationsresizingcroppingdrawingand other image manipulations will be done through method calls on this image object to shorten the examples in this 'll assume you've imported pillow' image module and that you have the zophie image stored in variable named catim be sure that the zophie png file is in the current working directory so that the image open(function can find it otherwiseyou will also have to specify the full absolute path in the string argument to image open(working with the image data type an image object has several useful attributes that give you basic information about the image file it was loaded fromits width and heightthe filenameand the graphics format (such as jpeggifor pngfor exampleenter the following into the interactive shellfrom pil import image catim image open('zophie png'manipulating images |
2,932 | ( widthheight catim size width height catim filename 'zophie pngcatim format 'pngcatim format_description 'portable network graphicsy catim save('zophie jpg'after making an image object from zophie png and storing the image object in catimwe can see that the object' size attribute contains tuple of the image' width and height in pixels we can assign the values in the tuple to width and height variables in order to access with width and height individually the filename attribute describes the original file' name the format and format_description attributes are strings that describe the image format of the original file (with format_description being bit more verbosefinallycalling the save(method and passing it 'zophie jpgsaves new image with the filename zophie jpg to your hard drive pillow sees that the file extension is jpg and automatically saves the image using the jpeg image format now you should have two imageszophie png and zophie jpgon your hard drive while these files are based on the same imagethey are not identical because of their different formats pillow also provides the image new(functionwhich returns an image object--much like image open()except the image represented by image new()' object will be blank the arguments to image new(are as followsthe string 'rgba'which sets the color mode to rgba (there are other modes that this book doesn' go into the sizeas two-integer tuple of the new image' width and height the background color that the image should start withas four-integer tuple of an rgba value you can use the return value of the imagecolor getcolor(function for this argument alternativelyimage new(also supports just passing the string of the standard color name for exampleenter the following into the interactive shellfrom pil import image im image new('rgba'( )'purple'im save('purpleimage png' im image new('rgba'( )im save('transparentimage png' |
2,933 | pixels tallwith purple background this image is then saved to the file purpleimage png we call image new(again to create another image objectthis time passing ( for the dimensions and nothing for the background color invisible black( )is the default color used if no color argument is specifiedso the second image has transparent backgroundwe save this transparent square in transparentimage png cropping images cropping an image means selecting rectangular region inside an image and removing everything outside the rectangle the crop(method on image objects takes box tuple and returns an image object representing the cropped image the cropping does not happen in place--that isthe original image object is left untouchedand the crop(method returns new image object remember that boxed tuple--in this casethe cropped section--includes the left column and top row of pixels but only goes up to and does not include the right column and bottom row of pixels enter the following into the interactive shellfrom pil import image catim image open('zophie png'croppedim catim crop(( )croppedim save('cropped png'this makes new image object for the cropped imagestores the object in croppedimand then calls save(on croppedim to save the cropped image in cropped png the new file cropped png will be created from the original imagelike in figure - figure - the new image will be just the cropped section of the original image manipulating images |
2,934 | the copy(method will return new image object with the same image as the image object it was called on this is useful if you need to make changes to an image but also want to keep an untouched version of the original for exampleenter the following into the interactive shellfrom pil import image catim image open('zophie png'catcopyim catim copy(the catim and catcopyim variables contain two separate image objectswhich both have the same image on them now that you have an image object stored in catcopyimyou can modify catcopyim as you like and save it to new filenameleaving zophie png untouched for examplelet' try modifying catcopyim with the paste(method the paste(method is called on an image object and pastes another image on top of it let' continue the shell example by pasting smaller image onto catcopyim faceim catim crop(( )faceim size ( catcopyim paste(faceim( )catcopyim paste(faceim( )catcopyim save('pasted png'first we pass crop( box tuple for the rectangular area in zophie png that contains zophie' face this creates an image object representing cropwhich we store in faceim now we can paste faceim onto catcopyim the paste(method takes two argumentsa "sourceimage object and tuple of the xand -coordinates where you want to paste the top-left corner of the source image object onto the main image object here we call paste(twice on catcopyimpassing ( the first time and ( the second time this pastes faceim onto catcopyim twiceonce with the top-left corner of faceim at ( on catcopyimand once with the top-left corner of faceim at ( finallywe save the modified catcopyim to pasted png the pasted png image looks like figure - note despite their namesthe copy(and paste(methods in pillow do not use your computer' clipboard note that the paste(method modifies its image object in placeit does not return an image object with the pasted image if you want to call paste(but also keep an untouched version of the original image aroundyou'll need to first copy the image and then call paste(on that copy |
2,935 | face pasted twice say you want to tile zophie' head across the entire imageas in figure - you can achieve this effect with just couple for loops continue the interactive shell example by entering the followingcatimwidthcatimheight catim size faceimwidthfaceimheight faceim size catcopytwo catim copy( for left in range( catimwidthfaceimwidth) for top in range( catimheightfaceimheight)print(lefttopcatcopytwo paste(faceim(lefttop) --snip- catcopytwo save('tiled png'manipulating images |
2,936 | with paste(to duplicate the cat' face ( dupli-catif you willhere we store the width of height of catim in catimwidth and catimheight at we make copy of catim and store it in catcopytwo now that we have copy that we can paste ontowe start looping to paste faceim onto catcopytwo the outer for loop' left variable starts at and increases by faceimwidth( the inner for loop' top variable start at and increases by faceimheight( these nested for loops produce values for left and top to paste grid of faceim images over the catcopytwo image objectas in figure - to see our nested loops workingwe print left and top after the pasting is completewe save the modified catcopytwo to tiled png resizing an image the resize(method is called on an image object and returns new image object of the specified width and height it accepts two-integer tuple argumentrepresenting the new width and height of the returned image enter the following into the interactive shellfrom pil import image catim image open('zophie png' widthheight catim size quartersizedim catim resize((int(width )int(height ))quartersizedim save('quartersized png' svelteim catim resize((widthheight )svelteim save('svelte png'here we assign the two values in the catim size tuple to the variables width and height using width and height instead of catim size[ and catim size[ makes the rest of the code more readable |
2,937 | int(height for the new height vso the image object returned from resize(will be half the length and width of the original imageor onequarter of the original image size overall the resize(method accepts only integers in its tuple argumentwhich is why you needed to wrap both divisions by in an int(call this resizing keeps the same proportions for the width and height but the new width and height passed to resize(do not have to be proportional to the original image the svelteim variable contains an image object that has the original width but height that is pixels taller wgiving zophie more slender look note that the resize(method does not edit the image object in place but instead returns new image object rotating and flipping images images can be rotated with the rotate(methodwhich returns new image object of the rotated image and leaves the original image object unchanged the argument to rotate(is single integer or float representing the number of degrees to rotate the image counterclockwise enter the following into the interactive shellfrom pil import image catim image open('zophie png'catim rotate( save('rotated png'catim rotate( save('rotated png'catim rotate( save('rotated png'note how you can chain method calls by calling save(directly on the image object returned from rotate(the first rotate(and save(call makes new image object representing the image rotated counterclockwise by degrees and saves the rotated image to rotated png the second and third calls do the samebut with degrees and degrees the results look like figure - figure - the original image (leftand the image rotated counterclockwise by and degrees notice that the width and height of the image change when the image is rotated or degrees if you rotate an image by some other amountthe original dimensions of the image are maintained on windowsa manipulating images |
2,938 | figure - on macostransparent pixels are used for the gaps instead the rotate(method has an optional expand keyword argument that can be set to true to enlarge the dimensions of the image to fit the entire rotated new image for exampleenter the following into the interactive shellcatim rotate( save('rotated png'catim rotate( expand=truesave('rotated _expanded png'the first call rotates the image degrees and saves it to rotate png (see the image on the left of figure - the second call rotates the image degrees with expand set to true and saves it to rotate _expanded png (see the image on the right of figure - figure - the image rotated degrees normally (leftand with expand=true (rightyou can also get "mirror flipof an image with the transpose(method you must pass either image flip_left_right or image flip_top_bottom to the transpose(method enter the following into the interactive shellcatim transpose(image flip_left_rightsave('horizontal_flip png'catim transpose(image flip_top_bottomsave('vertical_flip png'like rotate()transpose(creates new image object here we pass image flip_left_right to flip the image horizontally and then save the result to horizontal_flip png to flip the image verticallywe pass image flip_top_bottom and save to vertical_flip png the results look like figure - |
2,939 | changing individual pixels the color of an individual pixel can be retrieved or set with the getpixel(and putpixel(methods these methods both take tuple representing the xand -coordinates of the pixel the putpixel(method also takes an additional tuple argument for the color of the pixel this color argument is four-integer rgba tuple or three-integer rgb tuple enter the following into the interactive shellfrom pil import image im image new('rgba'( ) im getpixel(( )( for in range( )for in range( ) im putpixel((xy)( )from pil import imagecolor for in range( )for in range( ) im putpixel((xy)imagecolor getcolor('darkgray''rgba')im getpixel(( )( im getpixel(( )( im save('putpixel png'at we make new image that is transparent square calling getpixel(on some coordinates in this image returns ( because the image is transparent to color pixels in this imagewe can use nested for loops to go through all the pixels in the top half of the image and color each pixel using putpixel( here we pass putpixel(the rgb tuple ( ) light gray manipulating images |
2,940 | but don' know the rgb tuple for dark gray the putpixel(method doesn' accept standard color name like 'darkgray'so you have to use imagecolor getcolor(to get color tuple from 'darkgrayloop through the pixels in the bottom half of the image and pass putpixel(the return value of imagecolor getcolor(zand you should now have an image that is light gray in its top half and dark gray in the bottom halfas shown in figure - you can call getpixel(on some coordinates to confirm that the color at any given pixel is what you expect finallysave the image to putpixel png figure - the putpixel png image of coursedrawing one pixel at time onto an image isn' very convenient if you need to draw shapesuse the imagedraw functions explained later in this projectadding logo say you have the boring job of resizing thousands of images and adding small logo watermark to the corner of each doing this with basic graphics program such as paintbrush or paint would take forever fancier graphics application such as photoshop can do batch processingbut that software costs hundreds of dollars let' write script to do it instead say that figure - is the logo you want to add to the bottom-right corner of each imagea black cat icon with white borderwith the rest of the image transparent figure - the logo to be added to the image |
2,941 | load the logo image loop over all png and jpg files in the working directory check whether the image is wider or taller than pixels if soreduce the width or height (whichever is largerto pixels and scale down the other dimension proportionally paste the logo image into the corner save the altered images to another folder this means the code will need to do the following open the catlogo png file as an image object loop over the strings returned from os listdir('get the width and height of the image from the size attribute calculate the new width and height of the resized image call the resize(method to resize the image call the paste(method to paste the logo call the save(method to save the changesusing the original filename step open the logo image for this projectopen new file editor tabenter the following codeand save it as resizeandaddlogo py#python resizeandaddlogo py resizes all images in current working directory to fit in squareand adds catlogo png to the lower-right corner import os from pil import image square_fit_size logo_filename 'catlogo pngw logoim image open(logo_filenamex logowidthlogoheight logoim size todoloop over all files in the working directory todocheck if image needs to be resized todocalculate the new width and height to resize to todoresize the image todoadd the logo todosave changes manipulating images |
2,942 | start of the programwe've made it easy to change the program later say the logo that you're adding isn' the cat iconor say you're reducing the output imageslargest dimension to something other than pixels with these constants at the start of the programyou can just open the codechange those values onceand you're done (or you can make it so that the values for these constants are taken from the command line arguments without these constantsyou' instead have to search the code for all instances of and 'catlogo pngand replace them with the values for your new project in shortusing constants makes your program more generalized the logo image object is returned from image open( for readabilitylogowidth and logoheight are assigned to the values from logoim size the rest of the program is skeleton of todo comments for now step loop over all files and open images now you need to find every png file and jpg file in the current working directory you don' want to add the logo image to the logo image itselfso the program should skip any image with filename that' the same as logo_filename add the following to your code#python resizeandaddlogo py resizes all images in current working directory to fit in squareand adds catlogo png to the lower-right corner import os from pil import image --snip-os makedirs('withlogo'exist_ok=trueloop over all files in the working directory for filename in os listdir(') if not (filename endswith(png'or filename endswith(jpg')or filename =logo_filenamew continue skip non-image files and the logo file itself im image open(filenamewidthheight im size --snip-firstthe os makedirs(call creates withlogo folder to store the finished images with logosinstead of overwriting the original image files the exist_ok=true keyword argument will keep os makedirs(from raising an exception if withlogo already exists while looping through all the files in the working directory with os listdir('uthe long if statement checks whether each filename doesn' end with png or jpg if so--or if the file is the logo image itself--then the loop should skip it and use continue to go to the next file if filename does end with pngor jpg(and isn' the logo file)you can open it as an image object and set width and height |
2,943 | the program should resize the image only if the width or height is larger than square_fit_size ( pixelsin this case)so put all of the resizing code inside an if statement that checks the width and height variables add the following code to your program#python resizeandaddlogo py resizes all images in current working directory to fit in squareand adds catlogo png to the lower-right corner import os from pil import image --snip-check if image needs to be resized if width square_fit_size and height square_fit_sizecalculate the new width and height to resize to if width heightu height int((square_fit_size widthheightwidth square_fit_size elsev width int((square_fit_size heightwidthheight square_fit_size resize the image print('resizing % (filename) im im resize((widthheight)--snip-if the image does need to be resizedyou need to find out whether it is wide or tall image if width is greater than heightthen the height should be reduced by the same proportion that the width would be reduced this proportion is the square_fit_size value divided by the current width the new height value is this proportion multiplied by the current height value since the division operator returns float value and resize(requires the dimensions to be integersremember to convert the result to an integer with the int(function finallythe new width value will simply be set to square_fit_size if the height is greater than or equal to the width (both cases are handled in the else clause)then the same calculation is doneexcept with the height and width variables swapped once width and height contain the new image dimensionspass them to the resize(method and store the returned image object in im step add the logo and save the changes whether or not the image was resizedthe logo should still be pasted to the bottom-right corner where exactly the logo should be pasted depends on both the size of the image and the size of the logo figure - shows how manipulating images |
2,944 | logo will be the image width minus the logo widththe top coordinate for where to paste the logo will be the image height minus the logo height image width logo width logo height image height image logo figure - the left and top coordinates for placing the logo in the bottom-right corner should be the image width/height minus the logo width/height after your code pastes the logo into the imageit should save the modified image object add the following to your program#python resizeandaddlogo py resizes all images in current working directory to fit in squareand adds catlogo png to the lower-right corner import os from pil import image --snip-check if image needs to be resized --snip-add the logo print('adding logo to % (filename) im paste(logoim(width logowidthheight logoheight)logoimsave changes im save(os path join('withlogo'filename)the new code prints message telling the user that the logo is being added upastes logoim onto im at the calculated coordinates vand saves the changes to filename in the withlogo directory when you run this program with the zophie png file as the only image in the working directorythe output will look like thisresizing zophie png adding logo to zophie png |
2,945 | looks like figure - remember that the paste(method will not paste the transparency pixels if you do not pass the logoim for the third argument as well this program can automatically resize and "logo-ifyhundreds of images in just couple minutes figure - the image zophie png resized and the logo added (leftif you forget the third argumentthe transparent pixels in the logo will be copied as solid white pixels (rightideas for similar programs being able to composite images or modify image sizes in batch can be useful in many applications you could write similar programs to do the followingadd text or website url to images add timestamps to images copy or move images into different folders based on their sizes add mostly transparent watermark to an image to prevent others from copying it drawing on images if you need to draw linesrectanglescirclesor other simple shapes on an imageuse pillow' imagedraw module enter the following into the interactive shellfrom pil import imageimagedraw im image new('rgba'( )'white'draw imagedraw draw(immanipulating images |
2,946 | casea white imageand store the image object in im we pass the image object to the imagedraw draw(function to receive an imagedraw object this object has several methods for drawing shapes and text onto an image object store the imagedraw object in variable like draw so you can use it easily in the following example drawing shapes the following imagedraw methods draw various kinds of shapes on the image the fill and outline parameters for these methods are optional and will default to white if left unspecified points the point(xyfillmethod draws individual pixels the xy argument represents list of the points you want to draw the list can be list of xand -coordinate tuplessuch as [(xy)(xy)]or list of xand -coordinates without tuplessuch as [ the fill argument is the color of the points and is either an rgba tuple or string of color namesuch as 'redthe fill argument is optional lines the line(xyfillwidthmethod draws line or series of lines xy is either list of tuplessuch as [(xy)(xy)]or list of integerssuch as [ each point is one of the connecting points on the lines you're drawing the optional fill argument is the color of the linesas an rgba tuple or color name the optional width argument is the width of the lines and defaults to if left unspecified rectangles the rectangle(xyfilloutlinemethod draws rectangle the xy argument is box tuple of the form (lefttoprightbottomthe left and top values specify the xand -coordinates of the upper-left corner of the rectanglewhile right and bottom specify the lower-right corner the optional fill argument is the color that will fill the inside of the rectangle the optional outline argument is the color of the rectangle' outline ellipses the ellipse(xyfilloutlinemethod draws an ellipse if the width and height of the ellipse are identicalthis method will draw circle the xy argument is box tuple (lefttoprightbottomthat represents box that precisely contains the ellipse the optional fill argument is the color of the inside of the ellipseand the optional outline argument is the color of the ellipse' outline |
2,947 | the polygon(xyfilloutlinemethod draws an arbitrary polygon the xy argument is list of tuplessuch as [(xy)(xy)]or integerssuch as [ ]representing the connecting points of the polygon' sides the last pair of coordinates will be automatically connected to the first pair the optional fill argument is the color of the inside of the polygonand the optional outline argument is the color of the polygon' outline drawing example enter the following into the interactive shellfrom pil import imageimagedraw im image new('rgba'( )'white'draw imagedraw draw(imu draw line([( )( )( )( )( )]fill='black' draw rectangle(( )fill='blue' draw ellipse(( )fill='red' draw polygon((( )( )( )( )( ))fill='brown' for in range( )draw line([( )( )]fill='green'im save('drawing png'after making an image object for white imagepassing it to imagedraw draw(to get an imagedraw objectand storing the imagedraw object in drawyou can call drawing methods on draw here we make thinblack outline at the edges of the image ua blue rectangle with its top-left corner at ( and bottom-right corner at ( va red ellipse defined by box from ( to ( wa brown polygon with five points xand pattern of green lines drawn with for loop the resulting drawing png file will look like figure - figure - the resulting drawing png image manipulating images |
2,948 | the full documentation is available at /reference/imagedraw html drawing text the imagedraw object also has text(method for drawing text onto an image the text(method takes four argumentsxytextfilland font the xy argument is two-integer tuple specifying the upper-left corner of the text box the text argument is the string of text you want to write the optional fill argument is the color of the text the optional font argument is an imagefont objectused to set the typeface and size of the text this is described in more detail in the next section since it' often hard to know in advance what size block of text will be in given fontthe imagedraw module also offers textsize(method its first argument is the string of text you want to measureand its second argument is an optional imagefont object the textsize(method will then return twointeger tuple of the width and height that the text in the given font would be if it were written onto the image you can use this width and height to help you calculate exactly where you want to put the text on your image the first three arguments for text(are straightforward before we use text(to draw text onto an imagelet' look at the optional fourth argumentthe imagefont object both text(and textsize(take an optional imagefont object as their final arguments to create one of these objectsfirst run the followingfrom pil import imagefont now that you've imported pillow' imagefont moduleyou can call the imagefont truetype(functionwhich takes two arguments the first argument is string for the font' truetype file--this is the actual font file that lives on your hard drive truetype file has the ttf file extension and can usually be found in the following folderson windowsc:\windows\fonts on macos/library/fonts and /system/library/fonts on linux/usr/share/fonts/truetype you don' actually need to enter these paths as part of the truetype file string because python knows to automatically search for fonts in these directories but python will display an error if it is unable to find the font you specified the second argument to imagefont truetype(is an integer for the font size in points (rather thansaypixelskeep in mind that pillow creates png images that are pixels per inch by defaultand point is / of an inch |
2,949 | the actual folder name your operating system usesfrom pil import imageimagedrawimagefont import os im image new('rgba'( )'white' draw imagedraw draw(imw draw text(( )'hello'fill='purple'fontsfolder 'font_foldere '/library/fontsx arialfont imagefont truetype(os path join(fontsfolder'arial ttf') draw text(( )'howdy'fill='gray'font=arialfontim save('text png'after importing imageimagedrawimagefontand oswe make an image object for new white image and make an imagedraw object from the image object we use text(to draw hello at ( in purple we didn' pass the optional fourth argument in this text(callso the typeface and size of this text aren' customized to set typeface and sizewe first store the folder name (like /library /fontsin fontsfolder then we call imagefont truetype()passing it the ttf file for the font we wantfollowed by an integer font size store the font object you get from imagefont truetype(in variable like arialfontand then pass the variable to text(in the final keyword argument the text(call at draws howdy at ( in gray in -point arial the resulting text png file will look like figure - figure - the resulting text png image summary images consist of collection of pixelsand each pixel has an rgba value for its color and its addressable by xand -coordinates two common image formats are jpeg and png the pillow module can handle both of these image formats and others manipulating images |
2,950 | dimensions are stored as two-integer tuple in the size attribute objects of the image data type also have methods for common image manipulationscrop()copy()paste()resize()rotate()and transpose(to save the image object to an image filecall the save(method if you want your program to draw shapes onto an imageuse imagedraw methods to draw pointslinesrectanglesellipsesand polygons the module also provides methods for drawing text in typeface and font size of your choosing although advanced (and expensiveapplications such as photoshop provide automatic batch processing featuresyou can use python scripts to do many of the same modifications for free in the previous you wrote python programs to deal with plaintext filesspreadsheetspdfsand other formats with the pillow moduleyou've extended your programming powers to processing images as wellpractice questions what is an rgba valuehow can you get the rgba value of 'cornflowerbluefrom the pillow modulewhat is box tuplewhat function returns an image object forsayan image file named zophie pnghow can you find out the width and height of an image object' imagewhat method would you call to get image object for imageexcluding the lower-left quarter of itafter making changes to an image objecthow could you save it as an image filewhat module contains pillow' shape-drawing codeimage objects do not have drawing methods what kind of object doeshow do you get this kind of objectpractice projects for practicewrite programs that do the following extending and fixing the project programs the resizeandaddlogo py program in this works with png and jpeg filesbut pillow supports many more formats than just these two extend resizeandaddlogo py to process gif and bmp images as well another small issue is that the program modifies png and jpeg files only if their file extensions are set in lowercase for exampleit will process |
2,951 | check is case insensitive finallythe logo added to the bottom-right corner is meant to be just small markbut if the image is about the same size as the logo itselfthe result will look like figure - modify resizeandaddlogo py so that the image must be at least twice the width and height of the logo image before the logo is pasted otherwiseit should skip adding the logo figure - when the image isn' much larger than the logothe results look ugly identifying photo folders on the hard drive have bad habit of transferring files from my digital camera to temporary folders somewhere on the hard drive and then forgetting about these folders it would be nice to write program that could scan the entire hard drive and find these leftover "photo folders write program that goes through every folder on your hard drive and finds potential photo folders of coursefirst you'll have to define what you consider "photo folderto belet' say that it' any folder where more than half of the files are photos and how do you define what files are photosfirsta photo file must have the file extension png or jpg alsophotos are large imagesa photo file' width and height must both be larger than pixels this is safe betsince most digital camera photos are several thousand pixels in width and height as hinthere' rough skeleton of what this program might look like#python import modules and write comments to describe this program for foldernamesubfoldersfilenames in os walk(' :\\')numphotofiles numnonphotofiles for filename in filenamescheck if file extension isn' png or jpg manipulating images |
2,952 | numnonphotofiles + continue skip to next filename open image file using pillow check if width height are larger than if todoimage is large enough to be considered photo numphotofiles + elseimage is too small to be photo numnonphotofiles + if more than half of files were photosprint the absolute path of the folder if todoprint(todowhen the program runsit should print the absolute path of any photo folders to the screen custom seating cards included practice project to create custom invitations from list of guests in plaintext file as an additional projectuse the pillow module to create images for custom seating cards for your guests for each of the guests listed in the guests txt file from the resources at name and some flowery decoration public domain flower image is also available in the book' resources to ensure that each seating card is the same sizeadd black rectangle on the edges of the invitation image so that when the image is printed outthere will be guideline for cutting the png files that pillow produces are set to pixels per inchso -inch card would require -pixel image |
2,953 | controlling the ke yboard and mouse with gui au tom at ion knowing various python modules for editing spreadsheetsdownloading filesand launching programs is usefulbut sometimes there just aren' any modules for the applications you need to work with the ultimate tools for automating tasks on your computer are programs you write that directly control the keyboard and mouse these programs can control other applications by sending them virtual keystrokes and mouse clicksjust as if you were sitting at your computer and interacting with the applications yourself this technique is known as graphical user interface automationor gui automation for short with gui automationyour programs can do anything that human user sitting at the computer can doexcept spill coffee on the keyboard think of gui automation as programming robotic arm you can program the robotic arm to type at your keyboard and move your mouse for you this technique is particularly useful for tasks that involve lot of mindless clicking or filling out of forms |
2,954 | usually marketed as robotic process automation (rpathese products are effectively no different than the python scripts you can make yourself with the pyautogui modulewhich has functions for simulating mouse movementsbutton clicksand mouse wheel scrolls this covers only subset of pyautogui' featuresyou can find the full documentation at installing the pyautogui module the pyautogui module can send virtual keypresses and mouse clicks to windowsmacosand linux windows and macos users can simply use pip to install pyautogui howeverlinux users will first have to install some software that pyautogui depends on open terminal window and enter the following commandssudo apt-get install scrot sudo apt-get install python -tk sudo apt-get install python -dev to install pyautoguirun pip install --user pyautogui don' use sudo with pipyou may install modules to the python installation that the operating system usescausing conflicts with any scripts that rely on its original configuration howeveryou should use the sudo command when installing applications with apt-get appendix has complete information on installing third-party modules to test whether pyautogui has been installed correctlyrun import pyautogui from the interactive shell and check for any error messages warning don' save your program as pyautogui py when you run import pyautoguipython will import your program instead of the pyautogui and you'll get error messages like attributeerrormodule 'pyautoguihas no attribute 'clicksetting up accessibility apps on macos as security measuremacos doesn' normally let programs control the mouse or keyboard to make pyautogui work on macosyou must set the program running your python script to be an accessibility application without this stepyour pyautogui function calls will have no effect whether you run your python programs from muidleor the terminalhave that application open then open the system preferences and go to the accessibility tab the currently open applications will appear under the "allow the apps below to control your computerlabel check |
2,955 | you'll be prompted to enter your password to confirm these changes staying on track before you jump into gui automationyou should know how to escape problems that may arise python can move your mouse and type keystrokes at an incredible speed in factit might be too fast for other programs to keep up with alsoif something goes wrong but your program keeps moving the mouse aroundit will be hard to tell what exactly the program is doing or how to recover from the problem like the enchanted brooms from disney' the sorcerer' apprenticewhich kept filling--and then overfilling--mickey' tub with wateryour program could get out of control even though it' following your instructions perfectly stopping the program can be difficult if the mouse is moving around on its ownpreventing you from clicking the mu editor window to close it fortunatelythere are several ways to prevent or recover from gui automation problems pauses and fail-safes if your program has bug and you're unable to use the keyboard and mouse to shut it downyou can use pyautogui' fail-safe feature quickly slide the mouse to one of the four corners of the screen every pyautogui function call has th-of- -second delay after performing its action to give you enough time to move the mouse to corner if pyautogui then finds that the mouse cursor is in cornerit raises the pyautogui failsafeexception exception non-pyautogui instructions will not have this th-of- -second delay if you find yourself in situation where you need to stop your pyautogui programjust slam the mouse toward corner to stop it shutting down everything by logging out perhaps the simplest way to stop an out-of-control gui automation program is to log outwhich will shut down all running programs on windows and linuxthe logout hotkey is ctrl-altdel on macosit is shiftoption- by logging outyou'll lose any unsaved workbut at least you won' have to wait for full reboot of the computer controlling mouse movement in this sectionyou'll learn how to move the mouse and track its position on the screen using pyautoguibut first you need to understand how pyautogui works with coordinates the mouse functions of pyautogui use xand -coordinates figure - shows the coordinate system for the computer screenit' similar to the coordinate system used for imagesdiscussed in the originwhere controlling the keyboard and mouse with gui automation |
2,956 | all coordinates are positive integersthere are no negative coordinates increases ( , increases ( , ( , ( , figure - the coordinates of computer screen with resolution your resolution is how many pixels wide and tall your screen is if your screen' resolution is set to then the coordinate for the upperleft corner will be ( )and the coordinate for the bottom-right corner will be ( the pyautogui size(function returns two-integer tuple of the screen' width and height in pixels enter the following into the interactive shellimport pyautogui wh pyautogui size(obtain the screen resolution wh size(width= height= wh[ wh width the pyautogui size(function returns ( on computer with resolutiondepending on your screen' resolutionyour return value may be different the size object returned by size(is named tuple named tuples have numeric indexeslike regular tuplesand attribute nameslike objectsboth wh[ and wh width evaluate to the width of the screen (named tuples are beyond the scope of this book just remember that you can use them the same way you use tuples |
2,957 | now that you understand screen coordinateslet' move the mouse the pyautogui moveto(function will instantly move the mouse cursor to specified position on the screen integer values for the xand -coordinates make up the function' first and second argumentsrespectively an optional duration integer or float keyword argument specifies the number of seconds it should take to move the mouse to the destination if you leave it outthe default is for instantaneous movement (all of the duration keyword arguments in pyautogui functions are optional enter the following into the interactive shellimport pyautogui for in range( )move mouse in square pyautogui moveto( duration= pyautogui moveto( duration= pyautogui moveto( duration= pyautogui moveto( duration= this example moves the mouse cursor clockwise in square pattern among the four coordinates provided total of times each movement takes quarter of secondas specified by the duration= keyword argument if you hadn' passed third argument to any of the pyautogui moveto(callsthe mouse cursor would have instantly teleported from point to point the pyautogui move(function moves the mouse cursor relative to its current position the following example moves the mouse in the same square patternexcept it begins the square from wherever the mouse happens to be on the screen when the code starts runningimport pyautogui for in range( )pyautogui move( duration= pyautogui move( duration= pyautogui move(- duration= pyautogui move( - duration= right down left up the pyautogui move(function also takes three argumentshow many pixels to move horizontally to the righthow many pixels to move vertically downwardand (optionallyhow long it should take to complete the movement negative integer for the first or second argument will cause the mouse to move left or upwardrespectively getting the mouse position you can determine the mouse' current position by calling the pyautogui position(functionwhich will return point named tuple of the mouse cursor' and positions at the time of the function call enter the following into the interactive shellmoving the mouse around after each callpyautogui position(get current mouse position point( = = controlling the keyboard and mouse with gui automation |
2,958 | point( = = pyautogui position(and again point( = = [ the -coordinate is at index the -coordinate is also in the attribute of courseyour return values will vary depending on where your mouse cursor is controlling mouse interaction now that you know how to move the mouse and figure out where it is on the screenyou're ready to start clickingdraggingand scrolling clicking the mouse to send virtual mouse click to your computercall the pyautogui click(method by defaultthis click uses the left mouse button and takes place wherever the mouse cursor is currently located you can pass xand -coordinates of the click as optional first and second arguments if you want it to take place somewhere other than the mouse' current position if you want to specify which mouse button to useinclude the button keyword argumentwith value of 'left''middle'or 'rightfor examplepyautogui click( button='left'will click the left mouse button at the coordinates ( )while pyautogui click( button='right'will perform right-click at ( enter the following into the interactive shellimport pyautogui pyautogui click( move mouse to ( and click you should see the mouse pointer move to near the top-left corner of your screen and click once full "clickis defined as pushing mouse button down and then releasing it back up without moving the cursor you can also perform click by calling pyautogui mousedown()which only pushes the mouse button downand pyautogui mouseup()which only releases the button these functions have the same arguments as click()and in factthe click(function is just convenient wrapper around these two function calls as further conveniencethe pyautogui doubleclick(function will perform two clicks with the left mouse buttonwhile the pyautogui rightclick(and pyautogui middleclick(functions will perform click with the right and middle mouse buttonsrespectively |
2,959 | dragging means moving the mouse while holding down one of the mouse buttons for exampleyou can move files between folders by dragging the folder iconsor you can move appointments around in calendar app pyautogui provides the pyautogui dragto(and pyautogui drag(functions to drag the mouse cursor to new location or location relative to its current one the arguments for dragto(and drag(are the same as moveto(and move()the -coordinate/horizontal movementthe -coordinate/vertical movementand an optional duration of time (macos does not drag correctly when the mouse moves too quicklyso passing duration keyword argument is recommended to try these functionsopen graphics-drawing application such as ms paint on windowspaintbrush on macosor gnu paint on linux (if you don' have drawing applicationyou can use the online one at with the mouse cursor over the drawing application' canvas and the pencil or brush tool selectedenter the following into new file editor window and save it as spiraldraw pyimport pyautoguitime time sleep( pyautogui click(click to make the window active distance change while distance pyautogui drag(distance duration= move right distance distance change pyautogui drag( distanceduration= move down pyautogui drag(-distance duration= move left distance distance change pyautogui drag( -distanceduration= move up when you run this programthere will be five-second delay for you to move the mouse cursor over the drawing program' window with the pencil or brush tool selected then spiraldraw py will take control of the mouse and click to make the drawing program' window active the active window is the window that currently accepts keyboard inputand the actions you take--like typing orin this casedragging the mouse--will affect that window the active window is also known as the focused or foreground window once the drawing program is activespiraldraw py draws square spiral pattern like the one on the left of figure - while you can also create square spiral image by using the pillow module discussed in creating the image by controlling the mouse to draw it in ms paint lets you make use of this program' various brush styleslike in figure - on the rightas well as other advanced featureslike gradients or the fill bucket you can preselect the brush settings yourself (or have your python code select these settingsand then run the spiral-drawing program controlling the keyboard and mouse with gui automation |
2,960 | drawn with ms paint' different brushes the distance variable starts at so on the first iteration of the while loopthe first drag(call drags the cursor pixels to the righttaking seconds distance is then decreased to xand the second drag(call drags the cursor pixels down the third drag(call drags the cursor - horizontally ( to the leftzdistance is decreased to and the last drag(call drags the cursor pixels up on each iterationthe mouse is dragged rightdownleftand upand distance is slightly smaller than it was in the previous iteration by looping over this codeyou can move the mouse cursor to draw square spiral you could draw this spiral by hand (or ratherby mouse)but you' have to work slowly to be so precise pyautogui can do it in few secondsnote at the time of this writingpyautogui can' send mouse clicks or keystrokes to certain programssuch as antivirus software (to prevent viruses from disabling the softwareor video games on windows (which use different method of receiving mouse and keyboard inputyou can check the online documentation at readthedocs ioto see if these features have been added scrolling the mouse the final pyautogui mouse function is scroll()which you pass an integer argument for how many units you want to scroll the mouse up or down the size of unit varies for each operating system and applicationso you'll have to experiment to see exactly how far it scrolls in your particular situation |
2,961 | positive integer scrolls upand passing negative integer scrolls down run the following in mu editor' interactive shell while the mouse cursor is over the mu editor windowpyautogui scroll( you'll see mu scroll upward if the mouse cursor is over text field that can be scrolled up planning your mouse movements one of the difficulties of writing program that will automate clicking the screen is finding the xand -coordinates of the things you' like to click the pyautogui mouseinfo(function can help you with this the pyautogui mouseinfo(function is meant to be called from the interactive shellrather than as part of your program it launches small application named mouseinfo that' included with pyautogui the window for the application looks like figure - figure - the mouseinfo application' window enter the following into the interactive shellimport pyautogui pyautogui mouseinfo(this makes the mouseinfo window appear this window gives you information about the mouse' cursor current positionas well the color of the pixel underneath the mouse cursoras three-integer rgb tuple and as hex value the color itself appears in the color box in the window controlling the keyboard and mouse with gui automation |
2,962 | one of the eight copy or log buttons the copy allcopy xycopy rgband copy rgb hex buttons will copy their respective information to the clipboard the log alllog xylog rgband log rgb hex buttons will write their respective information to the large text field in the window you can save the text in this log text field by clicking the save log button by defaultthe sec button delay checkbox is checkedcausing three-second delay between clicking copy or log button and the copying or logging taking place this gives you short amount of time in which to click the button and then move the mouse into your desired position it may be easier to uncheck this boxmove the mouse into positionand press the to keys to copy or log the mouse position you can look at the copy and log menus at the top of the mouseinfo window to find out which key maps to which buttons for exampleuncheck the sec button delaythen move the mouse around the screen while pressing the buttonand notice how the xand -coordinates of the mouse are recorded in the large text field in the middle of the window you can later use these coordinates in your pyautogui scripts for more information on mouseinforeview the complete documentation at working with the screen your gui automation programs don' have to click and type blindly pyautogui has screenshot features that can create an image file based on the current contents of the screen these functions can also return pillow image object of the current screen' appearance if you've been skipping around in this bookyou'll want to read and install the pillow module before continuing with this section on linux computersthe scrot program needs to be installed to use the screenshot functions in pyautogui in terminal windowrun sudo apt-get install scrot to install this program if you're on windows or macosskip this step and continue with the section getting screenshot to take screenshots in pythoncall the pyautogui screenshot(function enter the following into the interactive shellimport pyautogui im pyautogui screenshot(the im variable will contain the image object of the screenshot you can now call methods on the image object in the im variablejust like any other image object has more information about image objects |
2,963 | say that one of the steps in your gui automation program is to click gray button before calling the click(methodyou could take screenshot and look at the pixel where the script is about to click if it' not the same gray as the gray buttonthen your program knows something is wrong maybe the window moved unexpectedlyor maybe pop-up dialog has blocked the button at this pointinstead of continuing--and possibly wreaking havoc by clicking the wrong thing--your program can "seethat it isn' clicking the right thing and stop itself you can obtain the rgb color value of particular pixel on the screen with the pixel(function enter the following into the interactive shellimport pyautogui pyautogui pixel(( )( pyautogui pixel(( )( pass pixel( tuple of coordinateslike ( or ( )and it'll tell you the color of the pixel at those coordinates in your image the return value from pixel(is an rgb tuple of three integers for the amount of redgreenand blue in the pixel (there is no fourth value for alphabecause screenshot images are fully opaque pyautogui' pixelmatchescolor(function will return true if the pixel at the given xand -coordinates on the screen matches the given color the first and second arguments are integers for the xand -coordinatesand the third argument is tuple of three integers for the rgb color the screen pixel must match enter the following into the interactive shellimport pyautogui pyautogui pixel(( )( pyautogui pixelmatchescolor( ( )true pyautogui pixelmatchescolor( ( )false after using pixel(to get an rgb tuple for the color of pixel at specific coordinates upass the same coordinates and rgb tuple to pixelmatchescolor(vwhich should return true then change value in the rgb tuple and call pixelmatchescolor(again for the same coordinates this should return false this method can be useful to call whenever your gui automation programs are about to call click(note that the color at the given coordinates must exactly match if it is even slightly different--for example( instead of ( )--then pixelmatchescolor(will return false controlling the keyboard and mouse with gui automation |
2,964 | but what if you do not know beforehand where pyautogui should clickyou can use image recognition instead give pyautogui an image of what you want to clickand let it figure out the coordinates for exampleif you have previously taken screenshot to capture the image of submit button in submit pngthe locateonscreen(function will return the coordinates where that image is found to see how locateonscreen(workstry taking screenshot of small area on your screenthen save the image and enter the following into the interactive shellreplacing 'submit pngwith the filename of your screenshotimport pyautogui pyautogui locateonscreen('submit png' box(left= top= width= height= [ left the box object is named tuple that locateonscreen(returns and has the -coordinate of the left edgethe -coordinate of the top edgethe widthand the height for the first place on the screen the image was found if you're trying this on your computer with your own screenshotyour return value will be different from the one shown here if the image cannot be found on the screenlocateonscreen(returns none note that the image on the screen must match the provided image perfectly in order to be recognized if the image is even pixel offlocateonscreen(raises an imagenotfoundexception exception if you've changed your screen resolutionimages from previous screenshots might not match the images on your current screen you can change the scaling in the display settings of your operating systemas shown in figure - figure - the scale display settings in windows (leftand macos (rightif the image can be found in several places on the screenlocateallonscreen(will return generator object generators are beyond the scope of this book |
2,965 | will be one four-integer tuple for each location where the image is found on the screen continue the interactive shell example by entering the following (and replacing 'submit pngwith your own image filename)list(pyautogui locateallonscreen('submit png')[( )( )each of the four-integer tuples represents an area on the screen in the example abovethe image appears in two locations if your image is only found in one areathen using list(and locateallonscreen(returns list containing just one tuple once you have the four-integer tuple for the specific image you want to selectyou can click the center of this area by passing the tuple to click(enter the following into the interactive shellpyautogui click(( )as shortcutyou can also pass the image filename directly to the click(functionpyautogui click('submit png'the moveto(and dragto(functions also accept image filename arguments remember locateonscreen(raises an exception if it can' find the image on the screenso you should call it from inside try statementtrylocation pyautogui locateonscreen('submit png'exceptprint('image could not be found 'without the try and except statementsthe uncaught exception would crash your program since you can' be sure that your program will always find the imageit' good idea to use the try and except statements when calling locateonscreen(getting window information image recognition is fragile way to find things on the screenif single pixel is different colorthen pyautogui locateonscreen(won' find the image if you need to find where particular window is on the screenit' faster and more reliable to use pyautogui' window features note as of version pyautogui' window features work only on windowsnot on macos or linux these features come from pyautogui' inclusion of the pygetwindow module controlling the keyboard and mouse with gui automation |
2,966 | the active window on your screen is the window currently in the foreground and accepting keyboard input if you're currently writing code in the mu editorthe mu editor' window is the active window of all the windows on your screenonly one will be active at time in the interactive shellcall the pyautogui getactivewindow(function to get window object (technically win window object when run on windowsonce you have that window objectyou can retrieve any of the object' attributeswhich describe its sizepositionand titleleftrighttopbottom single integer for the xor -coordinate of the window' side toplefttoprightbottomleftbottomright named tuple of two integers for the (xycoordinates of the window' corner midleftmidrightmidleftmidright named tuple of two integers for the (xycoordinate of the middle of the window' side widthheight single integer for one of the window' dimensionsin pixels size named tuple of two integers for the (widthheightof the window area single integer representing the area of the windowin pixels center named tuple of two integers for the (xycoordinate of the window' center centerxcentery single integer for the xor -coordinate of the window' center box named tuple of four integers for the (lefttopwidthheightmeasurements of the window title string of the text in the title bar at the top of the window to get the window' positionsizeand title information from the window objectfor exampleenter the following into the interactive shellimport pyautogui fw pyautogui getactivewindow(fw win window(hwnd= str(fw'<win window left=" "top=" "width=" "height=" "title="mu test py">fw title 'mu test pyfw size ( fw leftfw topfw rightfw bottom ( fw topleft ( |
2,967 | pyautogui click(fw left fw top you can now use these attributes to calculate precise coordinates within window if you know that button you want to click is always pixels to the right of and pixels down from the window' top-left cornerand the window' top-left corner is at screen coordinates ( )then calling pyautogui click( (or pyautogui click(fw left fw top if fw contains the window object for the windowwill click the button this wayyou won' have to rely on the slowerless reliable locateonscreen(function to find the button for you other ways of obtaining windows while getactivewindow(is useful for obtaining the window that is active at the time of the function callyou'll need to use some other function to obtain window objects for the other windows on the screen the following four functions return list of window objects if they're unable to find any windowsthey return an empty listreturns list of window objects for every visible window on the screen pyautogui getwindowsat(xyreturns list of window objects for every visible window that includes the point (xypyautogui getwindowswithtitle(titlereturns list of window objects for every visible window that includes the string title in its title bar pyautogui getactivewindow(returns the window object for the window that is currently receiving keyboard focus pyautogui getallwindows(pyautogui also has pyautogui getalltitles(functionwhich returns list of strings of every visible window manipulating windows windows attributes can do more than just tell you the size and position of the window you can also set their values in order to resize or move the window for exampleenter the following into the interactive shellimport pyautogui fw pyautogui getactivewindow( fw width gets the current width of the window fw topleft gets the current position of the window ( fw width resizes the width fw topleft ( moves the window controlling the keyboard and mouse with gui automation |
2,968 | about the window' size and position after calling these functions in mu editorthe window should move and become narrower was in figure - figure - the mu editor window before (topand after (bottomusing the window object attributes to move and resize it you can also find out and change the window' minimizedmaximizedand activated states try entering the following into the interactive shellimport pyautogui fw pyautogui getactivewindow( fw ismaximized returns true if window is maximized false fw isminimized returns true if window is minimized |
2,969 | fw isactive returns true if window is the active window true fw maximize(maximizes the window fw ismaximized true fw restore(undoes minimize/maximize action fw minimize(minimizes the window import time wait seconds while you activate different windowtime sleep( )fw activate(fw close(this will close the window you're typing in the ismaximized uisminimized vand isactive attributes contain boolean values that indicate whether the window is currently in that state the maximize(xminimize(zactivate({and restore( methods change the window' state after you maximize or minimize the window with maximize(or minimize()the restore(method will restore the window to its former size and position the close(method will close window be careful with this methodas it may bypass any message dialogs asking you to save your work before quitting the application the complete documentation for pyautogui' window-controlling feature can be found at features separately from pyautogui with the pygetwindow moduledocumented at controlling the keyboard pyautogui also has functions for sending virtual keypresses to your computerwhich enables you to fill out forms or enter text into applications sending string from the keyboard the pyautogui write(function sends virtual keypresses to the computer what these keypresses do depends on what window is active and what text field has focus you may want to first send mouse click to the text field you want in order to ensure that it has focus as simple examplelet' use python to automatically type the words helloworldinto file editor window firstopen new file editor window and position it in the upper-left corner of your screen so that pyautogui will click in the right place to bring it into focus nextenter the following into the interactive shellpyautogui click( )pyautogui write('helloworld!'notice how placing two commands on the same lineseparated by semicolonkeeps the interactive shell from prompting you for input between running the two instructions this prevents you from controlling the keyboard and mouse with gui automation |
2,970 | write(callswhich would mess up the example python will first send virtual mouse click to the coordinates ( )which should click the file editor window and put it in focus the write(call will send the text helloworldto the windowmaking it look like figure - you now have code that can type for youfigure - using pyautoggui to click the file editor window and type helloworldinto it by defaultthe write(function will type the full string instantly howeveryou can pass an optional second argument to add short pause between each character this second argument is an integer or float value of the number of seconds to pause for examplepyautogui write('helloworld!' will wait quarter-second after typing hanother quartersecond after eand so on this gradual typewriter effect may be useful for slower applications that can' process keystrokes fast enough to keep up with pyautogui for characters such as or !pyautogui will automatically simulate holding down the shift key as well key names not all keys are easy to represent with single text characters for examplehow do you represent shift or the left arrow key as single characterin pyautoguithese keyboard keys are represented by short string values instead'escfor the esc key or 'enterfor the enter key instead of single string argumenta list of these keyboard key strings can be passed to write(for examplethe following call presses the keythen the keythen the left arrow key twiceand finally the and keyspyautogui write([' '' ''left''left'' '' '] |
2,971 | output xyab table - lists the pyautogui keyboard key strings that you can pass to write(to simulate pressing any combination of keys you can also examine the pyautogui keyboard_keys list to see all possible keyboard key strings that pyautogui will accept the 'shiftstring refers to the left shift key and is equivalent to 'shiftleftthe same applies for 'ctrl''alt'and 'winstringsthey all refer to the left-side key table - pykeyboard attributes keyboard key string meaning ' '' '' '' '' '' '' '' '' ''!''@''#'and so on the keys for single characters 'enter(or 'returnor '\ 'the enter key 'escthe esc key 'shiftleft''shiftrightthe left and right shift keys 'altleft''altrightthe left and right alt keys 'ctrlleft''ctrlrightthe left and right ctrl keys 'tab(or '\ 'the tab key 'backspace''deletethe backspace and delete keys 'pageup''pagedownthe page up and page down keys 'home''endthe home and end keys 'up''down''left''rightthe updownleftand right arrow keys ' '' '' 'and so on the to keys 'volumemute''volumedown''volumeupthe mutevolume downand volume up keys (some keyboards do not have these keysbut your operating system will still be able to understand these simulated keypresses'pausethe pause key 'capslock''numlock''scrolllockthe caps locknum lockand scroll lock keys 'insertthe ins or insert key 'printscreenthe prtsc or print screen key 'winleft''winrightthe left and right win keys (on windows'commandthe command (key (on macos'optionthe option key (on macospressing and releasing the keyboard much like the mousedown(and mouseup(functionspyautogui keydown(and pyautogui keyup(will send virtual keypresses and releases to the computer they are passed keyboard key string (see table - for their argument for conveniencepyautogui provides the pyautogui press(functionwhich calls both of these functions to simulate complete keypress controlling the keyboard and mouse with gui automation |
2,972 | (obtained by holding the shift key and pressing )pyautogui keydown('shift')pyautogui press(' ')pyautogui keyup('shift'this line presses down shiftpresses (and releases and then releases shift if you need to type string into text fieldthe write(function is more suitable but for applications that take single-key commandsthe press(function is the simpler approach hotkey combinations hotkey or shortcut is combination of keypresses to invoke some application function the common hotkey for copying selection is ctrl- (on windows and linuxor - (on macosthe user presses and holds the ctrl keythen presses the keyand then releases the and ctrl keys to do this with pyautogui' keydown(and keyup(functionsyou would have to enter the followingpyautogui keydown('ctrl'pyautogui keydown(' 'pyautogui keyup(' 'pyautogui keyup('ctrl'this is rather complicated insteaduse the pyautogui hotkey(functionwhich takes multiple keyboard key string argumentspresses them in orderand releases them in the reverse order for the ctrl- examplethe code would simply be as followspyautogui hotkey('ctrl'' 'this function is especially useful for larger hotkey combinations in wordthe ctrl-altshift- hotkey combination displays the style pane instead of making eight different function calls (four keydown(calls and four keyup(calls)you can just call hotkey('ctrl''alt''shift'' 'setting up your gui automation scripts gui automation scripts are great way to automate the boring stuffbut your scripts can also be finicky if window is in the wrong place on desktop or some pop-up appears unexpectedlyyour script could be clicking on the wrong things on the screen here are some tips for setting up your gui automation scripts use the same screen resolution each time you run the script so that the position of windows doesn' change the application window that your script clicks should be maximized so that its buttons and menus are in the same place each time you run the script |
2,973 | add generous pauses while waiting for content to loadyou don' want your script to begin clicking before the application is ready use locateonscreen(to find buttons and menus to clickrather than relying on xy coordinates if your script can' find the thing it needs to clickstop the program rather than let it continue blindly clicking use getwindowswithtitle(to ensure that the application window you think your script is clicking on existsand use the activate(method to put that window in the foreground use the logging module from to keep log file of what your script has done this wayif you have to stop your script halfway through processyou can change it to pick up from where it left off add as many checks as you can to your script think about how it could fail if an unexpected pop-up window appears or if your computer loses its internet connection you may want to supervise the script when it first begins to ensure that it' working correctly you might also want to put pause at the start of your script so the user can set up the window the script will click on pyautogui has sleep(function that acts identically to time sleep((it just frees you from having to also add import time to your scriptsthere is also countdown(function that prints numbers counting down to give the user visual indication that the script will continue soon enter the following into the interactive shellimport pyautogui pyautogui sleep( pauses the program for seconds pyautogui countdown( counts down over seconds print('starting in 'end='')pyautogui countdown( starting in these tips can help make your gui automation scripts easier to use and more able to recover from unforeseen circumstances review of the pyautogui functions since this covered many different functionshere is quick summary referencemoves the mouse cursor to the given and coordinates move(xoffsetyoffsetmoves the mouse cursor relative to its current position dragto(xymoves the mouse cursor while the left button is held down drag(xoffsetyoffsetmoves the mouse cursor relative to its current position while the left button is held down click(xybuttonsimulates click (left button by defaultmoveto(xycontrolling the keyboard and mouse with gui automation |
2,974 | middleclick(simulates middle-button click doubleclick(simulates double left-button click mousedown(xybuttonsimulates pressing down the given button at the position xy mouseup(xybuttonsimulates releasing the given button at the position xy scroll(unitssimulates the scroll wheel positive argument scrolls upa negative argument scrolls down write(messagetypes the characters in the given message string write([key key key ]types the given keyboard key strings press(keypresses the given keyboard key string keydown(keysimulates pressing down the given keyboard key keyup(keysimulates releasing the given keyboard key hotkey([key key key ]simulates pressing the given keyboard key strings down in order and then releasing them in reverse order screenshot(returns screenshot as an image object (see for information on image objects getactivewindow()getallwindows()getwindowsat()and getwindowswithtitle(these functions return window objects that can resize and reposition application windows on the desktop getalltitles(returns list of strings of the title bar text of every window on the desktop rightclick( tch nd compu te thics "completely automated public turing test to tell computers and humans apartor "captchasare those small tests that ask you to type the letters in distorted picture or click on photos of fire hydrants these are tests that are easyif annoyingfor humans to pass but nearly impossible for software to solve after reading this you can see how easy it is to write script that couldsaysign up for billions of free email accounts or flood users with harassing messages captchas mitigate this by requiring step that only human can pass however not all websites implement captchasand these can be vulnerable to abuse by unethical programmers learning to code is powerful and exciting skilland you may be tempted to misuse this power for personal gain or even just to show off but just as an unlocked door isn' justification for trespassthe responsibility for your programs falls upon youthe programmer there is nothing clever about circumventing systems to cause harminvade privacyor gain unfair advantage hope that my efforts in writing this book enable you to become your most productive selfrather than mercenary one |
2,975 | of all the boring tasksfilling out forms is the most dreaded of chores it' only fitting that nowin the final projectyou will slay it say you have huge amount of data in spreadsheetand you have to tediously retype it into some other application' form interface--with no intern to do it for you although some applications will have an import feature that will allow you to upload spreadsheet with the informationsometimes it seems that there is no other way than mindlessly clicking and typing for hours on end you've come this far in this bookyou know that of course must be way to automate this boring task the form for this project is google docs form that you can find at figure - the form used for this project at high levelhere' what your program should do click the first text field of the form move through the formtyping information into each field click the submit button repeat the process with the next set of data controlling the keyboard and mouse with gui automation |
2,976 | call pyautogui click(to click the form and submit button call pyautogui write(to enter text into the fields handle the keyboardinterrupt exception so the user can press ctrl- to quit open new file editor window and save it as formfiller py step figure out the steps before writing codeyou need to figure out the exact keystrokes and mouse clicks that will fill out the form once the application launched by calling pyautogui mouseinfo(can help you figure out specific mouse coordinates you need to know only the coordinates of the first text field after clicking the first fieldyou can just press tab to move focus to the next field this will save you from having to figure out the xand -coordinates to click for every field here are the steps for entering data into the form put the keyboard focus on the name field so that pressing keys types text into the field type name and then press tab type greatest fear and then press tab press the down arrow key the correct number of times to select the wizard power sourceonce for wandtwice for amuletthree times for crystal balland four times for money then press tab (note that on macosyou will have to press the down arrow key one more time for each option for some browsersyou may need to press enter as well press the right arrow key to select the answer to the robocop question press it once for twice for three times for or four times for or just press the spacebar to select (which is highlighted by defaultthen press tab type an additional comment and then press tab press enter to "clickthe submit button after submitting the formthe browser will take you to page where you will need to follow link to return to the form page different browsers on different operating systems might work slightly differently from the steps given hereso check that these keystroke combinations work for your computer before running your program step set up coordinates load the example form you downloaded (figure - in browser by going to |
2,977 | #python formfiller py automatically fills in the form import pyautoguitime todogive the user chance to kill the script todowait until the form page has loaded todofill out the name field todofill out the greatest fear(sfield todofill out the source of wizard powers field todofill out the robocop field todofill out the additional comments field todoclick submit todowait until form page has loaded todoclick the submit another response link now you need the data you actually want to enter into this form in the real worldthis data might come from spreadsheeta plaintext fileor websiteand it would require additional code to load into the program but for this projectyou'll just hardcode all this data in variable add the following to your program#python formfiller py automatically fills in the form --snip-formdata [{'name''alice''fear''eavesdroppers''source''wand''robocop' 'comments''tell bob said hi '}{'name''bob''fear''bees''source''amulet''robocop' 'comments'' / '}{'name''carol''fear''puppets''source''crystal ball''robocop' 'comments''please take the puppets out of the break room '}{'name''alex murphy''fear''ed- ''source''money''robocop' 'comments''protect the innocent serve the public trust uphold the law '}--snip-controlling the keyboard and mouse with gui automation |
2,978 | each dictionary has names of text fields as keys and responses as values the last bit of setup is to set pyautogui' pause variable to wait half second after each function call alsoremind the user to click on the browser to make it the active window add the following to your program after the formdata assignment statementpyautogui pause print('ensure that the browser window is active and the form is loaded!'step start typing data for loop will iterate over each of the dictionaries in the formdata listpassing the values in the dictionary to the pyautogui functions that will virtually type in the text fields add the following code to your program#python formfiller py automatically fills in the form --snip-for person in formdatagive the user chance to kill the script print( -second pause to let user press ctrl- <<<' time sleep( --snip-as small safety featurethe script has five-second pause that gives the user chance to hit ctrl- (or move the mouse cursor to the upperleft corner of the screen to raise the failsafeexception exceptionto shut the program down in case it' doing something unexpected after the code that waits to give the page time to loadadd the following#python formfiller py automatically fills in the form --snip- print('entering % info (person['name']) pyautogui write(['\ ''\ ']fill out the name field pyautogui write(person['name''\ 'fill out the greatest fear(sfield pyautogui write(person['fear''\ '--snip- |
2,979 | terminal window to let the user know what' going on since the form has had time to loadcall pyautogui write(['\ ''\ ']to press tab twice and put the name field into focus then call write(again to enter the string in person['name' the '\tcharacter is added to the end of the string passed to write(to simulate pressing tabwhich moves the keyboard focus to the next fieldgreatest fear(sanother call to write(will type the string in person['fear'into this field and then tab to the next field in the form step handle select lists and radio buttons the drop-down menu for the "wizard powersquestion and the radio buttons for the robocop field are trickier to handle than the text fields to click these options with the mouseyou would have to figure out the xand -coordinates of each possible option it' easier to use the keyboard arrow keys to make selection instead add the following to your program#python formfiller py automatically fills in the form --snip-fill out the source of wizard powers field if person['source'='wand' pyautogui write(['down''\ ' elif person['source'='amulet'pyautogui write(['down''down''\ ' elif person['source'='crystal ball'pyautogui write(['down''down''down''\ ' elif person['source'='money'pyautogui write(['down''down''down''down''\ ' fill out the robocop field if person['robocop'= pyautogui write([''\ ' elif person['robocop'= pyautogui write(['right''\ ' elif person['robocop'= pyautogui write(['right''right''\ ' elif person['robocop'= pyautogui write(['right''right''right''\ ' elif person['robocop'= pyautogui write(['right''right''right''right''\ ' --snip-once the drop-down menu has focus (remember that you wrote code to simulate pressing tab after filling out the greatest fear(sfield)pressing the down arrow key will move to the next item in the selection list depending on the value in person['source']your program should send controlling the keyboard and mouse with gui automation |
2,980 | value at the 'sourcekey in this user' dictionary is 'wanduwe simulate pressing the down arrow key once (to select wandand pressing tab if the value at the 'sourcekey is 'amulet'we simulate pressing the down arrow key twice and pressing taband so on for the other possible answers the argument in these write(calls add half-second pause in between each key so that our program doesn' move too fast for the form the radio buttons for the robocop question can be selected with the right arrow keys--orif you want to select the first choice wby just pressing the spacebar step submit the form and wait you can fill out the additional comments field with the write(function by passing person['comments'as an argument you can type an additional '\tto move the keyboard focus to the next field or the submit button once the submit button is in focuscalling pyautogui press('enter'will simulate pressing the enter key and submit the form after submitting the formyour program will wait five seconds for the next page to load once the new page has loadedit will have submit another response link that will direct the browser to newempty form page you stored the coordinates of this link as tuple in submitanotherlink in step so pass these coordinates to pyautogui click(to click this link with the new form ready to gothe script' outer for loop can continue to the next iteration and enter the next person' information into the form complete your program by adding the following code#python formfiller py automatically fills in the form --snip-fill out the additional comments field pyautogui write(person['comments''\ '"clicksubmit button by pressing enter time sleep( wait for the button to activate pyautogui press('enter'wait until form page has loaded print('submitted form 'time sleep( click the submit another response link pyautogui click(submitanotherlink[ ]submitanotherlink[ ] |
2,981 | in the information for each person in this examplethere are only four people to enter but if you had , peoplethen writing program to do this would save you lot of time and typingdisplaying message boxes the programs you've been writing so far all tend to use plaintext output (with the print(functionand input (with the input(functionhoweverpyautogui programs will use your entire desktop as its playground the text-based window that your program runs inwhether it' mu or terminal windowwill probably be lost as your pyautogui program clicks and interacts with other windows this can make getting input and output from the user hard if the mu or terminal windows get hidden under other windows to solve thispyautogui offers pop-up message boxes to provide notifications to the user and receive input from them there are four message box functionspyautogui alert(textdisplays text and has single ok button pyautogui confirm(textdisplays text and has ok and cancel buttonsreturning either 'okor 'canceldepending on the button clicked displays text and has text field for the user to type inwhich it returns as string pyautogui password(textis the same as prompt()but displays asterisks so the user can enter sensitive information such as password pyautogui prompt(textthese functions also have an optional second parameter that accepts string value to use as the title in the title bar of the message box the functions won' return until the user has clicked button on themso they can also be used to introduce pauses into your pyautogui programs enter the following into the interactive shellimport pyautogui pyautogui alert('this is message ''important''okpyautogui confirm('do you want to continue?'click cancel 'cancelpyautogui prompt("what is your cat' name?"'zophiepyautogui password('what is the password?''hunter the pop-up message boxes that these lines produce look like figure - controlling the keyboard and mouse with gui automation |
2,982 | prompt()and password(these functions can be used to provide notifications or ask the user questions while the rest of the program interacts with the computer through the mouse and keyboard the full online documentation can be found at summary gui automation with the pyautogui module allows you to interact with applications on your computer by controlling the mouse and keyboard while this approach is flexible enough to do anything that human user can dothe downside is that these programs are fairly blind to what they are clicking or typing when writing gui automation programstry to ensure that they will crash quickly if they're given bad instructions crashing is annoyingbut it' much better than the program continuing in error you can move the mouse cursor around the screen and simulate mouse clickskeystrokesand keyboard shortcuts with pyautogui the pyautogui module can also check the colors on the screenwhich can provide your gui automation program with enough of an idea of the screen contents to know whether it has gotten offtrack you can even give pyautogui screenshot and let it figure out the coordinates of the area you want to click you can combine all of these pyautogui features to automate any mindlessly repetitive task on your computer in factit can be downright hypnotic to watch the mouse cursor move on its own and to see text appear on the screen automatically why not spend the time you saved by sitting back and watching your program do all your work for youthere' certain satisfaction that comes from seeing how your cleverness has saved you from the boring stuff |
2,983 | how can you trigger pyautogui' fail-safe to stop programwhat function returns the current resolution()what function returns the coordinates for the mouse cursor' current position what is the difference between pyautogui moveto(and pyautogui move() what functions can be used to drag the mouse what function call will type out the characters of "helloworld!" how can you do keypresses for special keys such as the keyboard' left arrow key how can you save the current contents of the screen to an image file named screenshot png what code would set two-second pause after every pyautogui function call if you want to automate clicks and keystrokes inside web browsershould you use pyautogui or selenium what makes pyautogui error-prone how can you find the size of every window on the screen that includes the text notepad in its title how can you makesaythe firefox browser active and in front of every other window on the screenpractice projects for practicewrite programs that do the following looking busy many instant messaging programs determine whether you are idleor away from your computerby detecting lack of mouse movement over some period of time--say minutes maybe you're away from your computer but don' want others to see your instant messenger status go into idle mode write script to nudge your mouse cursor slightly every seconds the nudge should be small and infrequent enough so that it won' get in the way if you do happen to need to use your computer while the script is running using the clipboard to read text field while you can send keystrokes to an application' text fields with pyautogui write()you can' use pyautogui alone to read the text already inside text field this is where the pyperclip module can help you can use pyautogui to obtain the window for text editor such as mu or notepadcontrolling the keyboard and mouse with gui automation |
2,984 | and then send the ctrl- or - hotkey to "select alland ctrl- or - hotkey to "copy to clipboard your python script can then read the clipboard text by running import pyperclip and pyperclip paste(write program that follows this procedure for copying the text from window' text fields use pyautogui getwindowswithtitle('notepad'(or whichever text editor you chooseto obtain window object the top and left attributes of this window object can tell you where this window iswhile the activate(method will ensure it is at the front of the screen you can then click the main text field of the text editor by addingsay or pixels to the top and left attribute values with pyautogui click(to put the keyboard focus there call pyautogui hotkey('ctrl'' 'and pyautogui hotkey('ctrl'' 'to select all the text and copy it to the clipboard finallycall pyperclip paste(to retrieve the text from the clipboard and paste it into your python program from thereyou can use this string however you wantbut just pass it to print(for now note that the window functions of pyautogui only work on windows as of pyautogui version and not on macos or linux instant messenger bot google talkskypeyahoo messengeraimand other instant messaging applications often use proprietary protocols that make it difficult for others to write python modules that can interact with these programs but even these proprietary protocols can' stop you from writing gui automation tool the google talk application has search bar that lets you enter username on your friend list and open messaging window when you press enter the keyboard focus automatically moves to the new window other instant messenger applications have similar ways to open new message windows write program that will automatically send out notification message to select group of people on your friend list your program may have to deal with exceptional casessuch as friends being offlinethe chat window appearing at different coordinates on the screenor confirmation boxes that interrupt your messaging your program will have to take screenshots to guide its gui interaction and adopt ways of detecting when its virtual keystrokes aren' being sent note you may want to set up some fake test accounts so that you don' accidentally spam your real friends while writing this program |
2,985 | there is great tutorial titled "how to build python bot that can play web gamesthat you can find link to at tutorial explains how to create gui automation program in python that plays flash game called sushi go round the game involves clicking the correct ingredient buttons to fill customerssushi orders the faster you fill orders without mistakesthe more points you get this is perfectly suited task for gui automation program--and way to cheat to high scorethe tutorial covers many of the same topics that this covers but also includes descriptions of pyautogui' basic image recognition features the source code for this bot is at video of the bot playing the game is at controlling the keyboard and mouse with gui automation |
2,986 | ins ta lling third-pa module many developers have written their own modulesextending python' capabilities beyond what is provided by the standard library of modules packaged with python the primary way to install third-party modules is to use python' pip tool this tool securely downloads and installs python modules onto your computer from the website of the python software foundation pypior the python package indexis sort of free app store for python modules the pip tool while pip comes automatically installed with python and later on windows and macosyou may have to install it separately on linux you can see whether pip is already installed on linux by running which pip in terminal window if it' installedyou'll see the location of pip displayed otherwisenothing will display to install pip on ubuntu or debian linux |
2,987 | to install pip on fedora linuxenter sudo yum install python -pip into terminal window you'll need to enter the administrator password for your computer the pip tool is run from terminal (also called command linewindownot from python' interactive shell on windowsrun the "command promptprogram from the start menu on macosrun terminal from spotlight on ubuntu linuxrun terminal from ubuntu dash or press ctrl alt- if pip' folder is not listed in the path environment variableyou may have to change directories in the terminal window with the cd command before running pip if you need to find out your usernamerun echo %usernameon windows or whoami on macos and linux then run cd pip folderwhere pip' folder is :\users\\appdata\local\programs \python\python \scripts on windows on macosit is in /library/frameworks /python framework/versions/ /binon linuxit is in /homelocal/binthen you'll be in the right folder to run the pip tool installing third-party modules the executable file for the pip tool is called pip on windows and pip on macos and linux from the command lineyou pass it the command install followed by the name of the module you want to install for exampleon windows you would enter pip install --user modulewhere module is the name of the module because future changes to these third-party modules may be backward incompatiblei recommend that you install the exact versions used in this bookas given later in this section you can add - module==version to the end of the module name to install particular version note that there are two equal signs in this command line option for examplepip install --user - send trash=installs version of the send trash module you can install all of the modules covered in this book by downloading the "requirementsfiles for your operating system from /automatestuff and running one of the following commandson windowspip install --user - automate-win-requirements txt --user on macospip install --user - automate-mac-requirements txt --user on linuxpip install --user - automate-linux-requirements txt --user appendix |
2,988 | along with their versions you can enter these commands separately if you only want to install few of these modules on your computer note pip install --user send trash=pip install --user openpyxl=pip install --user requests=pip install --user beautifulsoup =pip install --user selenium=pip install --user pypdf =pip install --user python-docx=(install python-docxnot docxpip install --user imapclient=pip install --user pyzmail =pip install --user twilio pip install --user ezgmail pip install --user ezsheets pip install --user pillow=pip install --user pyobjc-framework-quartz== (on macos onlypip install --user pyobjc-core== (on macos onlypip install --user pyobjc== (on macos onlypip install --user python -xlib== (on linux onlypip install --user pyautogui for macos usersthe pyobjc module can take minutes or longer to installso don' be alarmed if it takes while you should also install the pyobjc-core module firstwhich will reduce the overall installation time after installing moduleyou can test that it installed successfully by running import modulename in the interactive shell if no error messages are displayedyou can assume the module was installed successfully if you already have the module installed but would like to upgrade it to the latest version available on pypirun pip install --user - module (or pip install --user - module on macos and linuxthe --user option installs the module in your home directory this avoids potential permissions errors you might encounter when trying to install for all users the latest versions of the selenium and openpyxl modules tend to have changes that are backward incompatible with the versions used in this book on the other handthe twilioezgmailand ezsheets modules interact with online servicesand you might be required to install the latest version of these modules with the pip install --user - command installing third-party modules |
2,989 | the first edition of this book suggested using the sudo command if you encountered permission errors while running pipsudo pip install module this is bad practiceas it installs modules to the python installation used by your operating system your operating system may run python scripts to carry out system-related tasksand if you install modules to this python installation that conflict with its existing modulesyou could create hard-to-fix bugs never use sudo when installing python modules installing modules for the mu editor the mu editor has its own python environmentseparate from the one that typical python installations have to install modules so that you can use them in scripts launched by muyou must bring up the admin panel by clicking the gear icon in the lower-right corner of the mu editor in the window that appearsclick the third party packages tab and follow the instructions for installing modules on that tab the ability to install modules into mu is still an early feature under developmentso these instructions may change if you are unable to install modules using the admin panelyou can also open terminal window and run the pip tool specific to the mu editor you'll have to use pip' --target command line option to specify mu' module folder on windowsthis folder is :\users\appdata local\mu\pkgs on macosthis folder is /applications/mu-editor app/contents /resources/app_packages on linuxyou don' need to enter --target argumentjust run the pip command normally for exampleafter you download the requirements file for your operating system from on windowspip install - automate-win-requirements txt --target " :\users\usernameappdata\local\mu\pkgson macospip install - automate-mac-requirements txt --target /applicationsmu-editor app/contents/resources/app_packages on linuxpip install --user - automate-linux-requirements txt if you want to install only some of the modulesyou can run the regular pip (or pip command and add the --target argument appendix |
2,990 | running progr ams if you have program open in murunning it is simple matter of pressing or clicking the run button at the top of the window this is an easy way to run programs while writing thembut opening mu to run your finished programs can be burden there are more convenient ways to execute python scriptsdepending on which operating system you're using running programs from the terminal window when you open terminal window (such as command prompt on windows or terminal on macos and linux)you'll see mostly blank window into which you can enter text commands you can run your programs from the terminalbut if you're not used to itusing your computer through terminal (also called command linecan be intimidatingunlike graphical user interfaceit offers no hints about what you're supposed to do |
2,991 | command promptand press enter on macosclick on the spotlight icon in the upper righttype terminaland press enter on ubuntu linuxyou can press the win key to bring up dashtype terminaland press enter the keyboard shortcut ctrl-alt- will also open terminal window on ubuntu just as the interactive shell has promptthe terminal will display prompt for you to enter commands on windowsit will be the full path of the folder you are currently inc:\users\al>your commands go here on macosthe prompt shows your computer' namea colonthe current working directory (with your home folder represented as for short)and your usernamefollowed by dollar sign ($)als-macbook-pro:alyour commands go here on ubuntu linuxthe prompt is similar to macos'sexcept it begins with the username and an signal@al-virtualbox:~your commands go here it' possible to customize these promptsbut that' beyond the scope of this book when you enter commandlike python on windows or python on macos and linuxthe terminal checks for program with that name in the folder you're currently in if it doesn' find it thereit will check the folders listed in the path environment variable you can think of environment variables as variables for your entire operating system they'll contain few system settings to see the value stored in the path environment variablerun echo %pathon windows and echo $path on macos and linux here' an example on macosals-macbook-pro:alecho $path /library/frameworks/python framework/versions/ /bin:/usr/local/bin:/usrbin:/bin:/usr/sbin:/sbin on macosthe python program file is located in the /library/frameworks /python framework/versions/ /bin folderso you don' have to enter /library /frameworks/python framework/versions/ /bin/python or switch to that folder first to run ityou can enter python from any folderand the terminal will find it in one of the path environment variable' folders adding program' folder to the path environment variable is convenient shortcut if you want to run py programyou must enter python (or python followed by the py filename this will run pythonand in turn python will run the code it finds in that py file after the python program finishes appendix |
2,992 | "helloworld!program would look like thismicrosoft windows [version ( microsoft corporation all rights reserved :\users\al>python hello py helloworldc:\users\alrunning python (or python without any filename will cause python to launch the interactive shell running python programs on windows there are few other ways you can run python programs on windows instead of opening terminal window to run your python scriptsyou can press win- to open the run dialog box and enter py :\path\to\your \pythonscript pyas shown in figure - the py exe program is installed at :\windows\py exewhich is already in the path environment variableand typing the exe file extension is optional when running programs figure - the run dialog on windows the downside of this method is that you must enter the full path to your script alsowhile running your python script from the dialog box will open new terminal window to display its outputthis window will automatically close when the program endsand you might miss some output you can solve these problems by creating batch scriptwhich is small text file with the bat file extension that can run multiple terminal commandsmuch like shell script in macos and linux you can use text editor such as notepad to create these files to make batch filemake new text file containing single linelike this@py exe :\path\to\your\pythonscript py %@pause running programs |
2,993 | this file with bat file extension (for examplepythonscript batthe sign at the start of each command prevents it from being displayed in the terminal windowand the %forwards any command line arguments entered after the batch filename to the python script the python scriptin turnreads the command line arguments in the sys argv list this batch file will keep you from having to type the full absolute path for the python program every time you want to run it in addition@pause will add "press any key to continue after the end of the python script to prevent the program' window from disappearing too quickly recommend you place all your batch and py files in single folder that already exists in the path environment variablesuch as :\userswith batch file set up to run your python scriptyou don' need to open terminal window and type the full file path and name of your python script insteadjust press win-renter pythonscript (the full pythonscript bat name isn' necessary)and press enter to run your script running python programs on macos on macosyou can create shell script to run your python scripts by creating text file with the command file extension create new file in text editor such as textedit and add the following content#!/usr/bin/env bash python /path/to/your/pythonscript py save this file with the command file extension in your home folder (for exampleon my computer it' /users/alin terminal windowmake this shell script executable by running chmod + yourscript command now you will be able to click the spotlight icon (or press spaceand enter yourscript command to run the shell scriptwhich in turn will run your python script running python programs on ubuntu linux running your python scripts in ubuntu linux from the dash menu requires considerable setup let' say we have /home/al/example py script (your python script could be in different folder with different filenamethat we want to run from dash firstuse text editor such as gedit to create new file with the following content[desktop entryname=example py exec=gnome-terminal -/home/al/example sh type=application categories=gtk;gnome;utilitysave this file to the /home/local/share/applications folder (replacing al with your own usernameas example desktop if your text editor doesn' appendix |
2,994 | and open terminal window to move the file with the mv /home/al/example desktop /home/allocal/share/applications command when the example desktop file is in the /home/allocal/share/applications folderyou'll be able to press the windows key on your keyboard to bring up dash and type example py (or whatever you put for the name fieldthis opens new terminal window (specificallythe gnome-terminal programthat runs the /home/al/example sh shell scriptwhich we'll create next in the text editorcreate new file with the following content#!/usr/bin/env bash python /home/al/example py bash save this file to /home/al/example sh this is shell scripta script that runs series of terminal commands this shell script will run our /home/alexample py python script and then run the bash shell program without the bash command on the last linethe terminal window would close as soon as the python script finishes and you' miss any text that print(function calls put on the screen you'll need to add execute permissions to this shell scriptso run the following command from terminal windowal@ubuntu:~chmod + /home/al/example sh with the example desktop and example sh files set upyou'll now be able to run the example py script by pressing the windows key and entering example py (or whatever name you put in the name field of the example desktop filerunning python programs with assertions disabled you can disable the assert statements in your python programs to gain slight performance improvement when running python from the terminalinclude the - switch after python or python and before the name of the py file this will run an optimized version of your program that skips the assertion checks running programs |
2,995 | answers to the pr actice questions this appendix contains the answers to the practice problems at the end of each highly recommend that you take the time to work through these problems programming is more than memorizing syntax and list of function names as when learning foreign languagethe more practice you put into itthe more you will get out of it there are many websites with practice programming problems as well you can find list of these at when it comes to the practice projectsthere is no one correct program as long as your program performs what the project asks foryou can consider it correct howeverif you want to see examples of completed projectsthey are available in the "download the files used in the booklink at nostarch com/automatestuff |
2,996 | the operators are +-*and the values are 'hello'- and the variable is spamthe string is 'spamstrings always start and end with quotes the three data types introduced in this are integersfloatingpoint numbersand strings an expression is combination of values and operators all expressions evaluate (that isreduceto single value an expression evaluates to single value statement does not the bacon variable is set to the bacon expression does not reassign the value in bacon (that would need an assignment statementbacon bacon both expressions evaluate to the string 'spamspamspam variable names cannot begin with number the int()float()and str(functions will evaluate to the integerfloating-point numberand string versions of the value passed to them the expression causes an error because is an integerand only strings can be concatenated to other strings with the operator the correct way is have eaten str( burritos appendix true and falseusing capital and fwith the rest of the word in lowercase andorand not true and true is true true and false is false false and true is false false and false is false true or true is true true or false is true false or true is true false or false is false not true is false not false is true false false true false false true |
2,997 | ==!= condition is an expression used in flow control statement that evaluates to boolean value the three blocks are everything inside the if statement and the lines print('bacon'and print('ham' =is the equal to operator that compares two values and evaluates to booleanwhile is the assignment operator that stores value in variable print('eggs'if spam print('bacon'elseprint('ham'print('spam' the codeif spam = print('hello'elif spam = print('howdy'elseprint('greetings!' press ctrl- to stop program stuck in an infinite loop the break statement will move the execution outside and just after loop the continue statement will move the execution to the start of the loop they all do the same thing the range( call ranges from up to (but not including range( explicitly tells the loop to start at and range( explicitly tells the loop to increase the variable by on each iteration the codefor in range( )print(iandi while < print(ii this function can be called with spam bacon(answers to the practice questions |
2,998 | functions reduce the need for duplicate code this makes programs shortereasier to readand easier to update the code in function executes when the function is callednot when the function is defined the def statement defines (that iscreatesa function function consists of the def statement and the code in its def clause function call is what moves the program execution into the functionand the function call evaluates to the function' return value there is one global scopeand local scope is created whenever function is called when function returnsthe local scope is destroyedand all the variables in it are forgotten return value is the value that function call evaluates to like any valuea return value can be used as part of an expression if there is no return statement for functionits return value is none global statement will force variable in function to refer to the global variable the data type of none is nonetype that import statement imports module named areallyourpetsnamederic (this isn' real python moduleby the way this function could be called with spam bacon( place the line of code that might cause an error in try clause the code that could potentially cause an error goes in the try clause the code that executes if an error happens goes in the except clause appendix the empty list valuewhich is list value that contains no items this is similar to how 'is the empty string value spam[ 'hello(notice that the third value in list is at index because the first index is ' (note that ' is the string ' 'which is passed to int(before being divided by this eventually evaluates to expressions can be used wherever values are used ' (negative indexes count from the end [' '' ' [ 'cat' 'cat'true [ 'cat'true |
2,999 | the operator for list concatenation is +while the operator for replication is (this is the same as for strings while append(will add values only to the end of listinsert(can add them anywhere in the list the del statement and the remove(list method are two ways to remove values from list both lists and strings can be passed to len()have indexes and slicesbe used in for loopsbe concatenated or replicatedand be used with the in and not in operators lists are mutablethey can have values addedremovedor changed tuples are immutablethey cannot be changed at all alsotuples are written using parenthesesand )while lists use the square bracketsand ( ,(the trailing comma is mandatory the tuple(and list(functionsrespectively they contain references to list values the copy copy(function will do shallow copy of listwhile the copy deepcopy(function will do deep copy of list that isonly copy deepcopy(will duplicate any lists inside the list two curly brackets{{'foo' the items stored in dictionary are unorderedwhile the items in list are ordered you get keyerror error there is no difference the in operator checks whether value exists as key in the dictionary the 'catin spam checks whether there is 'catkey in the dictionarywhile 'catin spam values(checks whether there is value 'catfor one of the keys in spam spam setdefault('color''black'pprint pprint( escape characters represent characters in string values that would otherwise be difficult or impossible to type into code \ is newline\ is tab the \escape character will represent backslash character answers to the practice questions |
Subsets and Splits