How to fix Python 3 PyAutoGUI screenshot error? (macOS) - python-3.x

I keep getting an error with any of PyAutoGUI's screenshot taking functions such as:
pyautogui.locateOnScreen('button.png')
pyautogui.pixelMatchesColor(x, y, (r, g, b))
im = pyautogui.screenshot()
The error I get is:
screencapture: cannot write file to intended destination, .screenshot2018-1009_16-43-26-003190.png
Traceback (most recent call last):
File "~/program.py", line 111, in <module>
pyautogui.locateOnScreen('/images/play!.png')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyscreeze/__init__.py", line 265, in locateOnScreen
screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return accurate coordinates, so don't pass a region here.
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyscreeze/__init__.py", line 331, in _screenshot_osx
im = Image.open(tmpFilename)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/Image.py", line 2609, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '.screenshot2018-1009_16-43-26-003190.png'
I don't tell it to or want it to save the new screenshotted image to any directory (and it shouldn't). With the pyautogui.screenshot() function I could manually save it to a real directory in my project, but I don't have an option to do that with the other methods. Any idea on how to fix this?
What I've tried:
I looked at all the documentation I could find online of pyautogui screenshots
Restarting computer
Downgrading versions for Pillow and pyscreeze
EDIT:
I tried it on another mac and got the same error.
Tried it on windows bootcamp (windows on my mac) and it works fine.

possible, very hack-ish fix - I don't actually like this answer but it was a quick and easy fix (done on OSX with Mojave):
PLEASE NOTE: modifying the source code of libraries you don't understand is usually a bad idea, so do so at your own risk! This worked for me, your milage may vary.
Go to your file (your file path may be different, I just copied this from your error):
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyscreeze/__init__.py
find the line under the function "_screenshot_osx" that looks like
tmpFilename = '.screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f'))
copy it and then comment it out, paste the copied line directly below the commented out original and modify to something like this:
tmpFilename = r'<your preferred screenshot folder here>/screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f'))
save the changes, and see if it works.
Also note: pyautogui.locateOnScreen can be a bit finicky so even if this removes your error you still might not get the coordinates you want (might return none). That might be related to a different issue. To test that part I do this:
import pyautogui
pyautogui.screenshot('testFull.png')
placePos = pyautogui.locateOnScreen('testFull.png')
print(placePos)
even the cursor blinking can mess this up though, and osx has translucent user interfaces so it's kind of annoying to test this perfectly without careful image curation.

I was facing this same issue on MacOS Mojave after changing to Python 3.8.
Here is my solution.
Go the same file mentioned by #Richard W.
There, together with all your 'imports', add the following line so the script can find the tmpFilename folder
dirname = os.path.dirname(__file__)
then, replace the also mentioned line by
tmpFilename = os.path.join(dirname,r'screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f')))

Related

python problem creating file and using file by its name only like 'sample.txt' not by giving it path (using v s code)

enter image description here
every time i try using the file in python by using it name like 'sample.txt' terminal shows
no such file or directory
for solving it I had to provide the file path to it then only it works
solve the problem and provide me some steps by which I can surely avoid this problem next time
and read the terminal and provide the reason for it also it is showing
AttributeError: 'str' object has no attribute 'write'
please help me with this too.
thanks
Its necessary to open the file to print to it, and close it after. You will get the attribute error if you try to output to the file rather than the file object.
You can set the path and name of the file when you open it. See example below
demofile = open(r'c:\Temp\demofile.txt', 'w')
print(1,5,3,25,34, sep='->',end='!',file=demofile)
demofile.close()
Or using context manager to handle close
with open(r'c:\Temp\demofile.txt', 'w') as demofile:
print(1, 5, 3, 25, 34, sep='->', end='!', file=demofile)

How to add a new method to an existing import in python? Specifically moviepy

For whatever reason, Python is not allowing me to access a custom method I created in moviepy's preview.py file. I just want to know how to correctly implement it into the file. For reference, before I changed the name of the method, it was working correctly.
I checked at least two __init.py__ files and they were effectively empty. I couldn't find if methods are initialized anywhere, and is probably what I'm missing.
I also tried restarting Git Bash and that didn't work either (another solution I saw).
Original:
#convert_masks_to_RGB
def preview(clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
audio_nbytes=2, fullscreen=False):
Changed:
#requires_duration
#convert_masks_to_RGB
def preview_custom(clip, marker_overlay="marker_overlay.png", fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
audio_nbytes=2, fullscreen=False):
There are more than a few differences between the changed and original method, however at the moment the only result I expect is having the method be called correctly. Error is below:
Traceback (most recent call last):
File "T3AJM.py", line 249, in <module>
main()
File "T3AJM.py", line 34, in main
GUI_main_menu()
File "T3AJM.py", line 85, in GUI_main_menu
GUI_play_markers()
File "T3AJM.py", line 125, in GUI_play_markers
video.preview_custom(marker_overlay=TEMP_OVERLAY_FILE)
AttributeError: 'VideoFileClip' object has no attribute 'preview_custom'
Thank you for your time.
I'm not even sure if this technically fixes the problem, but just doing:
from moviepy.video.io.preview import *
and
preview_custom(video, marker_overlay=TEMP_OVERLAY_FILE)
fixed the problem. I have no idea why I had to change the way it was called, as doing clip.preview(), or in this case video.preview() worked perfectly fine before, but whatever.

PyTorch Fashion-MNIST (ETL)

I'm new to Deep Learning and PyTorch, so please do bear with me if some questions seem silly or I'm not asking in the correct format.
I was watching this video as part of a PyTorch series on Deep Learning: https://www.youtube.com/watch?v=8n-TGaBZnk4 . This video specifically is about ETL (using Fashion-MNIST dataset).
I have a few questions on the video at 7:05.
Question 1: In the Fashion-MNIST subclass constructor we passed it the argument:
‘root’, where the instructor mentioned: this is the location in disk where data is located. Sorry maybe this is a silly question, but is this where the data is located on the source server (from the URL) disk, or is this the path location where you want to save the data on your computer locally?
Question 2: Also for the Fashion-MNIST is the 'root' always the same location path: i.e. './data/FashionMNIST'?
Question 3: If the 'root' defines the location path where the data is located on the source server, then where would it be downloaded on locally? I checked my 'download' folder (I'm using Windows 7 laptop), and couldn't find the files there?
Question 4: The video mentioned that we should check if the data, in subsequent calls, are downloaded already or not (i.e. in the argument we pass download=true).
4(a): What's a good approach to do this? Do we put an if statement in place to check for this? Or is there a smarter way of checking for downloaded data?
4(b): Also what does it mean by "subsequent calls"? Does it mean when we need to call the 'FashionMNIST' constructor again for the test_data download?
Question 5: Finally, I tried running the code below (which is the one in the video) on Spyder IDE (Python 3.5):
import torch
import torchvision
import torchvision.transforms as transforms
train_set = torchvision.datasets.FashionMNIST(
root='./data/FashionMNIST'
,train=True
,download=True
,transform=transforms.Compose([
transforms.ToTensor()
])
)
I got the output:
Traceback (most recent call last):
File "<ipython-input-3-3ac000b9e90a>", line 10, in <module>
transforms.ToTensor()
File "C:\Program Files\Anaconda3\lib\site-packages\torchvision\datasets\mnist.py", line 68, in __init__
self.download()
File "C:\Program Files\Anaconda3\lib\site-packages\torchvision\datasets\mnist.py", line 136, in download
makedir_exist_ok(self.raw_folder)
File "C:\Program Files\Anaconda3\lib\site-packages\torchvision\datasets\utils.py", line 41, in makedir_exist_ok
os.makedirs(dirpath)
File "C:\Program Files\Anaconda3\lib\os.py", line 241, in makedirs
mkdir(name, mode)
FileNotFoundError: [WinError 206] The filename or extension is too long: './data/FashionMNIST\\FashionMNIST\\raw'
Not sure why I got that error at the end. In addition I ran the code on Jupyter Notebook, as per the video, and it worked fine. But I'm wondering why it throws that error in Spyder IDE.
Many thanks in advance.
No genuine question is a silly question, Answering questions one bye one:
Ans 1 & 2 :
root is the path on your local disk where the data will be saved, you can give ny path according to your liking it will not cause an issue.
Ans 3:
The urls etc are defined within the files and the path of the data is all you need to do: in order to look at the urls from where the data is downloaded here is a link.
Ans 4. : download = True merely gives it permission to download if the data doesn't exists the downloader will automatically check if the data already exists, if it exists it will still not download, even if download is set to be true, again it happens in the background you don't have to worry about it.
Ans5 : The issue isn't a torch issue exactly it has more to do with how it is being compiled on in windows, the issue is discussed at length here & here

Python 3 combining file open and read commands - a need to close a file and how?

I am working through "Learn Python 3 the Hard Way" and am making code more concise. Lines 11 to 18 of the program below (line 1 starts at # program: p17.py) are relevant to my question. Opening and reading a file are very easy and it is easy to see how you close the file you open when working with the files. The original section is commented out and I include the concise code on line 16. I commented out the line of code that causes an error (on line 20):
$ python3 p17_aside.py p17_text.txt p17_to_file_3.py
Copying from p17_text.txt to p17_to_file_3.py
This is text.
Traceback (most recent call last):
File "p17_aside.py", line 20, in
indata.close()
AttributeError: 'str' object has no attribute 'close'
Code is below:
# program: p17.py
# This program copies one file to another. It uses the argv function as well
# as exists - from sys and os.path modules respectively
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
# we could do these two on one line, how?
#in_file = open(from_file)
#indata = in_file.read()
#print(indata)
# THE ANSWER -
indata = open(from_file).read()
# The next line was used for testing
print(indata)
# indata.close()
So my question is should I just avoid the practice of combining commands as done above or is there a way to properly deal with that situation so files are closed when they should be? Is it necessary to deal with the situation of closing a file at all in this situation?
Context manager and with statement is a comfortable way to make sure your file is closed as needed:
with open(from_file) as fobj:
indata = fobj.read()
Nowadays, you can also use Path-like objects and their read_text and read_bytes methods:
# This assumes Path from pathlib has been imported
indata = Path(from_file).read_text()
The error you were seeing... is because you were not trying to close the file, but str into which you've read its content into. You'd need to assign object returned by open a name, and then read from and close that one:
fobj = open(from_file)
indata = fobj.read()
fobj.close() # This is OK
Strictly speaking, you would not need to close that file as dangling file descriptors would be "clobbered" with the process. Esp. in a short example like this, it would be of relatively little concern.
I hope I got the follow up question in comment correctly to extend on this a bit more.
If you wanted a single command, look at the pathtlib.Path example above.
With open as such, you cannot perform read and close in a single operation and without assigning result of open to a variable. As both read and close would have to be performed on the same object returned by open. If you do:
var = fobj.read()
Now, var refers to content read out of the file (so nothing that you could close, would have a close method).
If you did:
open(from_file).close()
After (but also before; at any point), you would simply open that file (again) and close it immediately. BTW. this returns None, just in case you wanted to get the return value. But it would not affect previously open file handles and file-like objects. It would not serve any practical purpose except for perhaps making sure you can open a file.
But again. It's a good practice to perform the housekeeping, but strictly speaking (and esp. in a short code like this). If you did not close the file and relied on the OS to clean-up after your process. It'd work fine.
How about the following:
# to open the file and read it
indata = open(from_file).read()
print(indata)
# this closes the file - just the opposite of opening and reading
open(from_file).close()

.txt file is acting weird under readlines()

The contents of the file look like this:
1/15/13,930,1441.5
1/15/13,1000,1442.75
1/15/13,1030,1444
I run:
the_txt_file = open('/txt_file')
Then I run:
the_txt_file_as_a_list = the_txt_file.readlines()
Then I run:
print the_txt_file_as_a_list
And I get this:
['1/15/13,930,1441.5\r1/15/13,1000,1442.75\r1/15/13,1030,1444\r1/']
But I was expecting something like:
['1/15/13,930,1441.5\n','15/13,1000,1442.75\n','15/13,1030,1444\n']
This happens to me pretty frequently, what is going on?
So it seems that the problem had something to do with the way my mac interacted with the .txt file
The problem was fixed by swapping:
the_txt_file = open('/txt_file')
with:
the_txt_file = open('/txt_file', 'rU')
The 'rU' is called 'universal-readline'. Opening a file in 'rU' mode is opening a file in Universal readline mode. Upon running:
the_txt_file_as_a_list = the_txt_file.readlines()
and then:
print the_txt_file_as_a_list
my output went from:
['1/15/13,930,1441.5\r1/15/13,1000,1442.75\r1/15/13,1030,1444\r1/']
to:
['1/15/13,930,1441.5\n', '1/15/13,1000,1442.75\n', '1/15/13,1030,1444\n']
Later, I was able to print each item seperatly by:
for item in the_txt_file_as_a_list:
print item
The output looked like:
1/15/13,930,1441.5
1/15/13,1000,1442.75
1/15/13,1030,1444
I would assume that you, or the original creator of this data file were on a Mac. Seems you are expecting it to be a simple '\n' line ending, but suffer from the originating editors system default line ending (most likely).
An easy fix, is to call open(...) with the rU option like so:
the_txt_file = open('/txt_file', 'rU')
This ensures that the file is opened read only, and uses Universal newline support when reading the particular file.
Good luck!

Resources