/
__init__.py
2171 lines (1764 loc) · 77.4 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# PyAutoGUI lets Python control the mouse and keyboard, and other GUI automation tasks. For Windows, macOS, and Linux,
# on Python 3 and 2.
# https://github.com/asweigart/pyautogui
# Al Sweigart al@inventwithpython.com (Send me feedback & suggestions!)
# TODO - the following features are half-implemented right now:
# snapshot logging
# non-qwerty keyboard mapping
# primary secondary mouse button awareness
from __future__ import absolute_import, division, print_function
__version__ = "0.9.54"
import collections
import sys
import time
import datetime
import os
import platform
import re
import functools
from contextlib import contextmanager
class PyAutoGUIException(Exception):
"""
PyAutoGUI code will raise this exception class for any invalid actions. If PyAutoGUI raises some other exception,
you should assume that this is caused by a bug in PyAutoGUI itself. (Including a failure to catch potential
exceptions raised by PyAutoGUI.)
"""
pass
class FailSafeException(PyAutoGUIException):
"""
This exception is raised by PyAutoGUI functions when the user puts the mouse cursor into one of the "failsafe
points" (by default, one of the four corners of the primary monitor). This exception shouldn't be caught; it's
meant to provide a way to terminate a misbehaving script.
"""
pass
class ImageNotFoundException(PyAutoGUIException):
"""
This exception is the PyAutoGUI version of PyScreeze's `ImageNotFoundException`, which is raised when a locate*()
function call is unable to find an image.
Ideally, `pyscreeze.ImageNotFoundException` should never be raised by PyAutoGUI.
"""
if sys.version_info[0] == 2 or sys.version_info[0:2] in ((3, 1), (3, 2)):
# Python 2 and 3.1 and 3.2 uses collections.Sequence
from collections import Sequence
else:
# Python 3.3+ uses collections.abc.Sequence
from collections.abc import Sequence
try:
from pytweening import (
easeInQuad,
easeOutQuad,
easeInOutQuad,
easeInCubic,
easeOutCubic,
easeInOutCubic,
easeInQuart,
easeOutQuart,
easeInOutQuart,
easeInQuint,
easeOutQuint,
easeInOutQuint,
easeInSine,
easeOutSine,
easeInOutSine,
easeInExpo,
easeOutExpo,
easeInOutExpo,
easeInCirc,
easeOutCirc,
easeInOutCirc,
easeInElastic,
easeOutElastic,
easeInOutElastic,
easeInBack,
easeOutBack,
easeInOutBack,
easeInBounce,
easeOutBounce,
easeInOutBounce,
)
# getLine is not needed.
# getPointOnLine has been redefined in this file, to avoid dependency on pytweening.
# linear has also been redefined in this file.
except ImportError:
def _couldNotImportPyTweening(*unused_args, **unused_kwargs):
"""
This function raises ``PyAutoGUIException``. It's used for the PyTweening function names if the PyTweening
module failed to be imported.
"""
raise PyAutoGUIException(
"PyAutoGUI was unable to import pytweening. Please install this module to enable the function you tried to call."
)
easeInQuad = _couldNotImportPyTweening
easeOutQuad = _couldNotImportPyTweening
easeInOutQuad = _couldNotImportPyTweening
easeInCubic = _couldNotImportPyTweening
easeOutCubic = _couldNotImportPyTweening
easeInOutCubic = _couldNotImportPyTweening
easeInQuart = _couldNotImportPyTweening
easeOutQuart = _couldNotImportPyTweening
easeInOutQuart = _couldNotImportPyTweening
easeInQuint = _couldNotImportPyTweening
easeOutQuint = _couldNotImportPyTweening
easeInOutQuint = _couldNotImportPyTweening
easeInSine = _couldNotImportPyTweening
easeOutSine = _couldNotImportPyTweening
easeInOutSine = _couldNotImportPyTweening
easeInExpo = _couldNotImportPyTweening
easeOutExpo = _couldNotImportPyTweening
easeInOutExpo = _couldNotImportPyTweening
easeInCirc = _couldNotImportPyTweening
easeOutCirc = _couldNotImportPyTweening
easeInOutCirc = _couldNotImportPyTweening
easeInElastic = _couldNotImportPyTweening
easeOutElastic = _couldNotImportPyTweening
easeInOutElastic = _couldNotImportPyTweening
easeInBack = _couldNotImportPyTweening
easeOutBack = _couldNotImportPyTweening
easeInOutBack = _couldNotImportPyTweening
easeInBounce = _couldNotImportPyTweening
easeOutBounce = _couldNotImportPyTweening
easeInOutBounce = _couldNotImportPyTweening
try:
from pymsgbox import alert, confirm, prompt, password
except ImportError:
# If pymsgbox module is not found, those methods will not be available.
def _couldNotImportPyMsgBox(*unused_args, **unused_kwargs):
"""
This function raises ``PyAutoGUIException``. It's used for the PyMsgBox function names if the PyMsgbox module
failed to be imported.
"""
raise PyAutoGUIException(
"PyAutoGUI was unable to import pymsgbox. Please install this module to enable the function you tried to call."
)
alert = confirm = prompt = password = _couldNotImportPyMsgBox
def raisePyAutoGUIImageNotFoundException(wrappedFunction):
"""
A decorator that wraps PyScreeze locate*() functions so that the PyAutoGUI user sees them raise PyAutoGUI's
ImageNotFoundException rather than PyScreeze's ImageNotFoundException. This is because PyScreeze should be
invisible to PyAutoGUI users.
"""
@functools.wraps(wrappedFunction)
def wrapper(*args, **kwargs):
try:
return wrappedFunction(*args, **kwargs)
except pyscreeze.ImageNotFoundException:
raise ImageNotFoundException # Raise PyAutoGUI's ImageNotFoundException.
return wrapper
try:
import pyscreeze
from pyscreeze import center, pixel, pixelMatchesColor, screenshot
# Change the locate*() functions so that they raise PyAutoGUI's ImageNotFoundException instead.
@raisePyAutoGUIImageNotFoundException
def locate(*args, **kwargs):
return pyscreeze.locate(*args, **kwargs)
locate.__doc__ = pyscreeze.locate.__doc__
@raisePyAutoGUIImageNotFoundException
def locateAll(*args, **kwargs):
return pyscreeze.locateAll(*args, **kwargs)
locateAll.__doc__ = pyscreeze.locateAll.__doc__
@raisePyAutoGUIImageNotFoundException
def locateAllOnScreen(*args, **kwargs):
return pyscreeze.locateAllOnScreen(*args, **kwargs)
locateAllOnScreen.__doc__ = pyscreeze.locateAllOnScreen.__doc__
@raisePyAutoGUIImageNotFoundException
def locateCenterOnScreen(*args, **kwargs):
return pyscreeze.locateCenterOnScreen(*args, **kwargs)
locateCenterOnScreen.__doc__ = pyscreeze.locateCenterOnScreen.__doc__
@raisePyAutoGUIImageNotFoundException
def locateOnScreen(*args, **kwargs):
return pyscreeze.locateOnScreen(*args, **kwargs)
locateOnScreen.__doc__ = pyscreeze.locateOnScreen.__doc__
@raisePyAutoGUIImageNotFoundException
def locateOnWindow(*args, **kwargs):
return pyscreeze.locateOnWindow(*args, **kwargs)
locateOnWindow.__doc__ = pyscreeze.locateOnWindow.__doc__
except ImportError:
# If pyscreeze module is not found, screenshot-related features will simply not work.
def _couldNotImportPyScreeze(*unused_args, **unsed_kwargs):
"""
This function raises ``PyAutoGUIException``. It's used for the PyScreeze function names if the PyScreeze module
failed to be imported.
"""
raise PyAutoGUIException(
"PyAutoGUI was unable to import pyscreeze. (This is likely because you're running a version of Python that Pillow (which pyscreeze depends on) doesn't support currently.) Please install this module to enable the function you tried to call."
)
center = _couldNotImportPyScreeze
#grab = _couldNotImportPyScreeze # grab() was removed, use screenshot() instead
locate = _couldNotImportPyScreeze
locateAll = _couldNotImportPyScreeze
locateAllOnScreen = _couldNotImportPyScreeze
locateCenterOnScreen = _couldNotImportPyScreeze
locateOnScreen = _couldNotImportPyScreeze
locateOnWindow = _couldNotImportPyScreeze
pixel = _couldNotImportPyScreeze
pixelMatchesColor = _couldNotImportPyScreeze
screenshot = _couldNotImportPyScreeze
try:
import mouseinfo
def mouseInfo():
"""
Launches the MouseInfo app. This application provides mouse coordinate information which can be useful when
planning GUI automation tasks. This function blocks until the application is closed.
"""
mouseinfo.MouseInfoWindow()
except ImportError:
def mouseInfo():
"""
This function raises PyAutoGUIException. It's used for the MouseInfo function names if the MouseInfo module
failed to be imported.
"""
raise PyAutoGUIException(
"PyAutoGUI was unable to import mouseinfo. Please install this module to enable the function you tried to call."
)
def useImageNotFoundException(value=None):
"""
When called with no arguments, PyAutoGUI will raise ImageNotFoundException when the PyScreeze locate*() functions
can't find the image it was told to locate. The default behavior is to return None. Call this function with no
arguments (or with True as the argument) to have exceptions raised, which is a better practice.
You can also disable raising exceptions by passing False for the argument.
"""
if value is None:
value = True
# TODO - this will cause a NameError if PyScreeze couldn't be imported:
try:
pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION = value
except NameError:
raise PyAutoGUIException("useImageNotFoundException() ws called but pyscreeze isn't installed.")
if sys.platform == "win32": # PyGetWindow currently only supports Windows.
try:
from pygetwindow import (
Window,
getActiveWindow,
getActiveWindowTitle,
getWindowsAt,
getWindowsWithTitle,
getAllWindows,
getAllTitles,
)
except ImportError:
# If pygetwindow module is not found, those methods will not be available.
def _couldNotImportPyGetWindow(*unused_args, **unused_kwargs):
"""
This function raises PyAutoGUIException. It's used for the PyGetWindow function names if the PyGetWindow
module failed to be imported.
"""
raise PyAutoGUIException(
"PyAutoGUI was unable to import pygetwindow. Please install this module to enable the function you tried to call."
)
Window = _couldNotImportPyGetWindow
getActiveWindow = _couldNotImportPyGetWindow
getActiveWindowTitle = _couldNotImportPyGetWindow
getWindowsAt = _couldNotImportPyGetWindow
getWindowsWithTitle = _couldNotImportPyGetWindow
getAllWindows = _couldNotImportPyGetWindow
getAllTitles = _couldNotImportPyGetWindow
KEY_NAMES = [
"\t",
"\n",
"\r",
" ",
"!",
'"',
"#",
"$",
"%",
"&",
"'",
"(",
")",
"*",
"+",
",",
"-",
".",
"/",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
":",
";",
"<",
"=",
">",
"?",
"@",
"[",
"\\",
"]",
"^",
"_",
"`",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"{",
"|",
"}",
"~",
"accept",
"add",
"alt",
"altleft",
"altright",
"apps",
"backspace",
"browserback",
"browserfavorites",
"browserforward",
"browserhome",
"browserrefresh",
"browsersearch",
"browserstop",
"capslock",
"clear",
"convert",
"ctrl",
"ctrlleft",
"ctrlright",
"decimal",
"del",
"delete",
"divide",
"down",
"end",
"enter",
"esc",
"escape",
"execute",
"f1",
"f10",
"f11",
"f12",
"f13",
"f14",
"f15",
"f16",
"f17",
"f18",
"f19",
"f2",
"f20",
"f21",
"f22",
"f23",
"f24",
"f3",
"f4",
"f5",
"f6",
"f7",
"f8",
"f9",
"final",
"fn",
"hanguel",
"hangul",
"hanja",
"help",
"home",
"insert",
"junja",
"kana",
"kanji",
"launchapp1",
"launchapp2",
"launchmail",
"launchmediaselect",
"left",
"modechange",
"multiply",
"nexttrack",
"nonconvert",
"num0",
"num1",
"num2",
"num3",
"num4",
"num5",
"num6",
"num7",
"num8",
"num9",
"numlock",
"pagedown",
"pageup",
"pause",
"pgdn",
"pgup",
"playpause",
"prevtrack",
"print",
"printscreen",
"prntscrn",
"prtsc",
"prtscr",
"return",
"right",
"scrolllock",
"select",
"separator",
"shift",
"shiftleft",
"shiftright",
"sleep",
"space",
"stop",
"subtract",
"tab",
"up",
"volumedown",
"volumemute",
"volumeup",
"win",
"winleft",
"winright",
"yen",
"command",
"option",
"optionleft",
"optionright",
]
KEYBOARD_KEYS = KEY_NAMES # keeping old KEYBOARD_KEYS for backwards compatibility
# Constants for the mouse button names:
LEFT = "left"
MIDDLE = "middle"
RIGHT = "right"
PRIMARY = "primary"
SECONDARY = "secondary"
# Different keyboard mappings:
# TODO - finish this feature.
# NOTE: Eventually, I'd like to come up with a better system than this. For now, this seems like it works.
QWERTY = r"""`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?"""
QWERTZ = r"""=1234567890/0qwertzuiop89-asdfghjkl,\yxcvbnm,.7+!@#$%^&*()?)QWERTZUIOP*(_ASDFGHJKL<|YXCVBNM<>&"""
def isShiftCharacter(character):
"""
Returns True if the ``character`` is a keyboard key that would require the shift key to be held down, such as
uppercase letters or the symbols on the keyboard's number row.
"""
# NOTE TODO - This will be different for non-qwerty keyboards.
return character.isupper() or character in set('~!@#$%^&*()_+{}|:"<>?')
# The platformModule is where we reference the platform-specific functions.
if sys.platform.startswith("java"):
# from . import _pyautogui_java as platformModule
raise NotImplementedError("Jython is not yet supported by PyAutoGUI.")
elif sys.platform == "darwin":
from . import _pyautogui_osx as platformModule
elif sys.platform == "win32":
from . import _pyautogui_win as platformModule
elif platform.system() == "Linux":
from . import _pyautogui_x11 as platformModule
else:
raise NotImplementedError("Your platform (%s) is not supported by PyAutoGUI." % (platform.system()))
# TODO: Having module-wide user-writable global variables is bad. It makes
# restructuring the code very difficult. For instance, what if we decide to
# move the mouse-related functions to a separate file (a submodule)? How that
# file will access this module vars? It will probably lead to a circular
# import.
# In seconds. Any duration less than this is rounded to 0.0 to instantly move
# the mouse.
MINIMUM_DURATION = 0.1
# If sleep_amount is less than MINIMUM_DURATION, time.sleep() will be a no-op and the mouse cursor moves there instantly.
# TODO: This value should vary with the platform. http://stackoverflow.com/q/1133857
MINIMUM_SLEEP = 0.05
# The number of seconds to pause after EVERY public function call. Useful for debugging:
PAUSE = 0.1 # Tenth-second pause by default.
# Interface need some catch up time on darwin (macOS) systems. Possible values probably differ based on your system performance.
# This value affects mouse moveTo, dragTo and key event duration.
# TODO: Find a dynamic way to let the system catch up instead of blocking with a magic number.
DARWIN_CATCH_UP_TIME = 0.01
# If the mouse is over a coordinate in FAILSAFE_POINTS and FAILSAFE is True, the FailSafeException is raised.
# The rest of the points are added to the FAILSAFE_POINTS list at the bottom of this file, after size() has been defined.
# The points are for the corners of the screen, but note that these points don't automatically change if the screen resolution changes.
FAILSAFE = True
FAILSAFE_POINTS = [(0, 0)]
LOG_SCREENSHOTS = False # If True, save screenshots for clicks and key presses.
# If not None, PyAutoGUI deletes old screenshots when this limit has been reached:
LOG_SCREENSHOTS_LIMIT = 10
G_LOG_SCREENSHOTS_FILENAMES = [] # TODO - make this a deque
Point = collections.namedtuple("Point", "x y")
Size = collections.namedtuple("Size", "width height")
def _genericPyAutoGUIChecks(wrappedFunction):
"""
A decorator that calls failSafeCheck() before the decorated function and
_handlePause() after it.
"""
@functools.wraps(wrappedFunction)
def wrapper(*args, **kwargs):
failSafeCheck()
returnVal = wrappedFunction(*args, **kwargs)
_handlePause(kwargs.get("_pause", True))
return returnVal
return wrapper
# General Functions
# =================
def getPointOnLine(x1, y1, x2, y2, n):
"""
Returns an (x, y) tuple of the point that has progressed a proportion ``n`` along the line defined by the two
``x1``, ``y1`` and ``x2``, ``y2`` coordinates.
This function was copied from pytweening module, so that it can be called even if PyTweening is not installed.
"""
x = ((x2 - x1) * n) + x1
y = ((y2 - y1) * n) + y1
return (x, y)
def linear(n):
"""
Returns ``n``, where ``n`` is the float argument between ``0.0`` and ``1.0``. This function is for the default
linear tween for mouse moving functions.
This function was copied from PyTweening module, so that it can be called even if PyTweening is not installed.
"""
# We use this function instead of pytweening.linear for the default tween function just in case pytweening couldn't be imported.
if not 0.0 <= n <= 1.0:
raise PyAutoGUIException("Argument must be between 0.0 and 1.0.")
return n
def _handlePause(_pause):
"""
A helper function for performing a pause at the end of a PyAutoGUI function based on some settings.
If ``_pause`` is ``True``, then sleep for ``PAUSE`` seconds (the global pause setting).
"""
if _pause:
assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
time.sleep(PAUSE)
def _normalizeXYArgs(firstArg, secondArg):
"""
Returns a ``Point`` object based on ``firstArg`` and ``secondArg``, which are the first two arguments passed to
several PyAutoGUI functions. If ``firstArg`` and ``secondArg`` are both ``None``, returns the current mouse cursor
position.
``firstArg`` and ``secondArg`` can be integers, a sequence of integers, or a string representing an image filename
to find on the screen (and return the center coordinates of).
"""
if firstArg is None and secondArg is None:
return position()
elif firstArg is None and secondArg is not None:
return Point(int(position()[0]), int(secondArg))
elif secondArg is None and firstArg is not None and not isinstance(firstArg, Sequence):
return Point(int(firstArg), int(position()[1]))
elif isinstance(firstArg, str):
# If x is a string, we assume it's an image filename to locate on the screen:
try:
location = locateOnScreen(firstArg)
# The following code only runs if pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION is not set to True, meaning that
# locateOnScreen() returns None if the image can't be found.
if location is not None:
return center(location)
else:
return None
except pyscreeze.ImageNotFoundException:
raise ImageNotFoundException
return center(locateOnScreen(firstArg))
elif isinstance(firstArg, Sequence):
if len(firstArg) == 2:
# firstArg is a two-integer tuple: (x, y)
if secondArg is None:
return Point(int(firstArg[0]), int(firstArg[1]))
else:
raise PyAutoGUIException(
"When passing a sequence for firstArg, secondArg must not be passed (received {0}).".format(
repr(secondArg)
)
)
elif len(firstArg) == 4:
# firstArg is a four-integer tuple, (left, top, width, height), we should return the center point
if secondArg is None:
return center(firstArg)
else:
raise PyAutoGUIException(
"When passing a sequence for firstArg, secondArg must not be passed and default to None (received {0}).".format(
repr(secondArg)
)
)
else:
raise PyAutoGUIException(
"The supplied sequence must have exactly 2 or exactly 4 elements ({0} were received).".format(
len(firstArg)
)
)
else:
return Point(int(firstArg), int(secondArg)) # firstArg and secondArg are just x and y number values
def _logScreenshot(logScreenshot, funcName, funcArgs, folder="."):
"""
A helper function that creates a screenshot to act as a logging mechanism. When a PyAutoGUI function is called,
this function is also called to capture the state of the screen when that function was called.
If ``logScreenshot`` is ``False`` (or None and the ``LOG_SCREENSHOTS`` constant is ``False``), no screenshot is taken.
The ``funcName`` argument is a string of the calling function's name. It's used in the screenshot's filename.
The ``funcArgs`` argument is a string describing the arguments passed to the calling function. It's limited to
twelve characters to keep it short.
The ``folder`` argument is the folder to place the screenshot file in, and defaults to the current working directory.
"""
if not logScreenshot:
return # Don't take a screenshot.
if logScreenshot is None and LOG_SCREENSHOTS is False:
return # Don't take a screenshot.
# Ensure that the "specifics" string isn't too long for the filename:
if len(funcArgs) > 12:
funcArgs = funcArgs[:12] + "..."
now = datetime.datetime.now()
filename = "%s-%s-%s_%s-%s-%s-%s_%s_%s.png" % (
now.year,
str(now.month).rjust(2, "0"),
str(now.day).rjust(2, "0"),
now.hour,
now.minute,
now.second,
str(now.microsecond)[:3],
funcName,
funcArgs,
)
filepath = os.path.join(folder, filename)
# Delete the oldest screenshot if we've reached the maximum:
if (LOG_SCREENSHOTS_LIMIT is not None) and (len(G_LOG_SCREENSHOTS_FILENAMES) >= LOG_SCREENSHOTS_LIMIT):
os.unlink(os.path.join(folder, G_LOG_SCREENSHOTS_FILENAMES[0]))
del G_LOG_SCREENSHOTS_FILENAMES[0]
screenshot(filepath)
G_LOG_SCREENSHOTS_FILENAMES.append(filename)
def position(x=None, y=None):
"""
Returns the current xy coordinates of the mouse cursor as a two-integer tuple.
Args:
x (int, None, optional) - If not None, this argument overrides the x in
the return value.
y (int, None, optional) - If not None, this argument overrides the y in
the return value.
Returns:
(x, y) tuple of the current xy coordinates of the mouse cursor.
NOTE: The position() function doesn't check for failsafe.
"""
posx, posy = platformModule._position()
posx = int(posx)
posy = int(posy)
if x is not None: # If set, the x parameter overrides the return value.
posx = int(x)
if y is not None: # If set, the y parameter overrides the return value.
posy = int(y)
return Point(posx, posy)
def size():
"""Returns the width and height of the screen as a two-integer tuple.
Returns:
(width, height) tuple of the screen size, in pixels.
"""
return Size(*platformModule._size())
resolution = size # resolution() is an alias for size()
def onScreen(x, y=None):
"""Returns whether the given xy coordinates are on the primary screen or not.
Note that this function doesn't work for secondary screens.
Args:
Either the arguments are two separate values, first arg for x and second
for y, or there is a single argument of a sequence with two values, the
first x and the second y.
Example: onScreen(x, y) or onScreen([x, y])
Returns:
bool: True if the xy coordinates are on the screen at its current
resolution, otherwise False.
"""
x, y = _normalizeXYArgs(x, y)
x = int(x)
y = int(y)
width, height = platformModule._size()
return 0 <= x < width and 0 <= y < height
# Mouse Functions
# ===============
"""
NOTE: Although "mouse1" and "mouse2" buttons usually refer to the left and
right mouse buttons respectively, in PyAutoGUI 1, 2, and 3 refer to the left,
middle, and right buttons, respectively. This is because Xlib interprets
button 2 as the middle button and button 3 as the right button, so we hold
that for Windows and macOS as well (since those operating systems don't use
button numbers but rather just "left" or "right").
"""
def _normalizeButton(button):
"""
The left, middle, and right mouse buttons are button numbers 1, 2, and 3 respectively. This is the numbering that
Xlib on Linux uses (while Windows and macOS don't care about numbers; they just use "left" and "right").
This function takes one of ``LEFT``, ``MIDDLE``, ``RIGHT``, ``PRIMARY``, ``SECONDARY``, ``1``, ``2``, ``3``, ``4``,
``5``, ``6``, or ``7`` for the button argument and returns either ``LEFT``, ``MIDDLE``, ``RIGHT``, ``4``, ``5``,
``6``, or ``7``. The ``PRIMARY``, ``SECONDARY``, ``1``, ``2``, and ``3`` values are never returned.
The ``'left'`` and ``'right'`` mouse buttons will always refer to the physical left and right
buttons on the mouse. The same applies for buttons 1 and 3.
However, if ``button`` is ``'primary'`` or ``'secondary'``, then we must check if
the mouse buttons have been "swapped" (for left-handed users) by the operating system's mouse
settings.
If the buttons are swapped, the primary button is the right mouse button and the secondary button is the left mouse
button. If not swapped, the primary and secondary buttons are the left and right buttons, respectively.
NOTE: Swap detection has not been implemented yet.
"""
# TODO - The swap detection hasn't been done yet. For Windows, see https://stackoverflow.com/questions/45627956/check-if-mouse-buttons-are-swapped-or-not-in-c
# TODO - We should check the OS settings to see if it's a left-hand setup, where button 1 would be "right".
# Check that `button` has a valid value:
button = button.lower()
if platform.system() == "Linux":
# Check for valid button arg on Linux:
if button not in (LEFT, MIDDLE, RIGHT, PRIMARY, SECONDARY, 1, 2, 3, 4, 5, 6, 7):
raise PyAutoGUIException(
"button argument must be one of ('left', 'middle', 'right', 'primary', 'secondary', 1, 2, 3, 4, 5, 6, 7)"
)
else:
# Check for valid button arg on Windows and macOS:
if button not in (LEFT, MIDDLE, RIGHT, PRIMARY, SECONDARY, 1, 2, 3):
raise PyAutoGUIException(
"button argument must be one of ('left', 'middle', 'right', 'primary', 'secondary', 1, 2, 3)"
)
# TODO - Check if the primary/secondary mouse buttons have been swapped:
if button in (PRIMARY, SECONDARY):
swapped = platformModule._mouse_is_swapped()
if swapped:
if button == PRIMARY:
return RIGHT
elif button == SECONDARY:
return LEFT
else:
if button == PRIMARY:
return LEFT
elif button == SECONDARY:
return RIGHT
# Return a mouse button integer value, not a string like 'left':
return {LEFT: LEFT, MIDDLE: MIDDLE, RIGHT: RIGHT, 1: LEFT, 2: MIDDLE, 3: RIGHT, 4: 4, 5: 5, 6: 6, 7: 7}[button]
@_genericPyAutoGUIChecks
def mouseDown(x=None, y=None, button=PRIMARY, duration=0.0, tween=linear, logScreenshot=None, _pause=True):
"""Performs pressing a mouse button down (but not up).
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge of the
screen.
Args:
x (int, float, None, tuple, optional): The x position on the screen where the
mouse down happens. None by default. If tuple, this is used for x and y.
If x is a str, it's considered a filename of an image to find on
the screen with locateOnScreen() and click the center of.
y (int, float, None, optional): The y position on the screen where the
mouse down happens. None by default.
button (str, int, optional): The mouse button pressed down. TODO
Returns:
None
Raises:
PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, or 3
"""
button = _normalizeButton(button)
x, y = _normalizeXYArgs(x, y)
_mouseMoveDrag("move", x, y, 0, 0, duration=0, tween=None)
_logScreenshot(logScreenshot, "mouseDown", "%s,%s" % (x, y), folder=".")
platformModule._mouseDown(x, y, button)
@_genericPyAutoGUIChecks
def mouseUp(x=None, y=None, button=PRIMARY, duration=0.0, tween=linear, logScreenshot=None, _pause=True):
"""Performs releasing a mouse button up (but not down beforehand).
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge of the
screen.
Args:
x (int, float, None, tuple, optional): The x position on the screen where the
mouse up happens. None by default. If tuple, this is used for x and y.
If x is a str, it's considered a filename of an image to find on
the screen with locateOnScreen() and click the center of.
y (int, float, None, optional): The y position on the screen where the
mouse up happens. None by default.
button (str, int, optional): The mouse button released. TODO
Returns:
None
Raises:
PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, or 3
"""
button = _normalizeButton(button)
x, y = _normalizeXYArgs(x, y)
_mouseMoveDrag("move", x, y, 0, 0, duration=0, tween=None)
_logScreenshot(logScreenshot, "mouseUp", "%s,%s" % (x, y), folder=".")
platformModule._mouseUp(x, y, button)
@_genericPyAutoGUIChecks
def click(
x=None, y=None, clicks=1, interval=0.0, button=PRIMARY, duration=0.0, tween=linear, logScreenshot=None, _pause=True
):
"""
Performs pressing a mouse button down and then immediately releasing it. Returns ``None``.
When no arguments are passed, the primary mouse button is clicked at the mouse cursor's current location.
If integers for ``x`` and ``y`` are passed, the click will happen at that XY coordinate. If ``x`` is a string, the
string is an image filename that PyAutoGUI will attempt to locate on the screen and click the center of. If ``x``
is a sequence of two coordinates, those coordinates will be used for the XY coordinate to click on.
The ``clicks`` argument is an int of how many clicks to make, and defaults to ``1``.
The ``interval`` argument is an int or float of how many seconds to wait in between each click, if ``clicks`` is
greater than ``1``. It defaults to ``0.0`` for no pause in between clicks.
The ``button`` argument is one of the constants ``LEFT``, ``MIDDLE``, ``RIGHT``, ``PRIMARY``, or ``SECONDARY``.
It defaults to ``PRIMARY`` (which is the left mouse button, unless the operating system has been set for
left-handed users.)
If ``x`` and ``y`` are specified, and the click is not happening at the mouse cursor's current location, then
the ``duration`` argument is an int or float of how many seconds it should take to move the mouse to the XY
coordinates. It defaults to ``0`` for an instant move.
If ``x`` and ``y`` are specified and ``duration`` is not ``0``, the ``tween`` argument is a tweening function
that specifies the movement pattern of the mouse cursor as it moves to the XY coordinates. The default is a
simple linear tween. See the PyTweening module documentation for more details.
The ``pause`` parameter is deprecated. Call the ``pyautogui.sleep()`` function to implement a pause.
Raises:
PyAutoGUIException: If button is not one of 'left', 'middle', 'right', 1, 2, 3
"""
# TODO: I'm leaving buttons 4, 5, 6, and 7 undocumented for now. I need to understand how they work.
button = _normalizeButton(button)
x, y = _normalizeXYArgs(x, y)
# Move the mouse cursor to the x, y coordinate:
_mouseMoveDrag("move", x, y, 0, 0, duration, tween)
_logScreenshot(logScreenshot, "click", "%s,%s,%s,%s" % (button, clicks, x, y), folder=".")
if sys.platform == 'darwin':
for i in range(clicks):
failSafeCheck()
if button in (LEFT, MIDDLE, RIGHT):
platformModule._multiClick(x, y, button, 1, interval)
else:
for i in range(clicks):
failSafeCheck()
if button in (LEFT, MIDDLE, RIGHT):