How to catch Permission Error with Popen process - python

This is the error:
Permission Error: Copying of text from this document is not allowed.
I am opening a .exe file on windows. So regular try except block does not seem to catch it. Neither does OSError.

I solved it with the following:
try:
"""code here"""
except subprocess.CalledProcessError:
"""unlock files and try again"""

Try
exception PermissionError
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES and EPERM.
If you specified irrelevant Exception while trying to catch permission error, I wouldn't be surprised they it is caught

Related

How to make Python "not recognized as an internal or external command" an exception

I have this block of code:
path = askdirectory(title='Choose folder')
os.chdir(path)
try:
os.system('currency.py')
except:
#Error message
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
What I want to accomplish is that when the user chooses the wrong folder (the one in which the 'currency.py' file is not in), it throws this little Error message box.
Instead, when I purposely choose the wrong folder, it says:
"currency.py "is not recognized as an internal or external command
But it doesn't show me the error window. Is there a way to make python recognize this error as an exception? Thank you!
It appears you are using Python to run a Python file using the operating system shell.
You can run the file by importing it and (if needed) instantiating it.
try:
# import the python file
import currency.py
# instantiate the class/function if required
except ImportError:
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
Nevertheless you can avoid using the try/catch scenario by seeing if the file exists, if not, display your error message:
if os.path.isfile(file_path):
os.system('currency.py')
else:
ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
You could try listening for the %ErrorLevel% code for anything different than 0 (successful) and, if it matches, then raise Exception.
It would work like this, for example:
if os.system('currency.py'):
raise Exception

How note a wrong password with Python's UnRAR library?

The following code (which tries to “open” an encrypted RAR-file supplying a wrong password):
from unrar import rarfile
import unrar
try:
rarfile.RarFile("encrypted.rar", pwd="wrong_password")
except Exception as e:
print(type(e))
print(e)
mostly, though nothing else is wrong with the RAR-file (can be decrypted without errors by using the correct password), outputs:
<class 'unrar.rarfile.BadRarFile'>
Invalid RAR file.
but sometimes it outputs:
<class 'RuntimeError'>
Bad password for Archive
How do I check if a password for a RAR-file is correct with Python's UnRAR library without chaining the exceptions?
In short: UnRAR library raises (randomly?) different exception for the same type of error (namely, wrong password supplied). In most of the cases it raises BadRarFile but sometimes it raises RuntimeError. Catching RuntimeError is bad enough (yet here we can at least check the args), but if one also catches except unrar.rarfile.BadRarFile, one cannot even differentiate between the error that (a) the password is wrong or (b) that the RAR-file is bad.
You could chain multiple except to narrow down the error. Unfortunately, your unrar library seems to raise the unspecific exception RuntimeError in case a bad password is provided. So you cannot be 100% sure if a bad password is the reason for the error.
try:
unrar.rarfile.RarFile("encrypted.rar", pwd="wrong_password")
except unrar.rarfile.BadRarFile:
print("Specified file doesn't seem to be a proper RAR archive")
except RuntimeError:
print("RuntimeError, possibly a wrong password")
except:
print("Something else happened")
Other than using different error messages "Wrong password or defective file" and "Wrong password or something else", unfortunately, I don't see any possibility for improvement.
In short: UnRAR library raises (randomly?) different exception for the same type of error (namely, wrong password supplied). In most of the cases it raises BadRarFile but sometimes it raises RuntimeError.
It's possible that depending on the version of the RAR file specs, there have been changes how a bad password is being handled. Maybe it isn't possible to differentiate between corrupt files and a wrong password with RAR files of a newer version while this was possible for older files. (Or the other way around.)
If the "original" unrar command doesn't have this issue, it's possibly a bug upstream in your Python wrapper library.

operation not permitted error on Linux Python

I am using shutil copy to copy the text file from one location to other. But it is throwing exception:
Operation not permitted.
But surprisingly I can see that the file is copied to destination folder. Then why it is throwing exception? I am using below code.
import shutil
old_name='/test/test1.txt'
new_name='/test1/test1.txt'
try:
shutil.copy(old_name, new_name)
except IOError as e:
print(e)
Have you tried using sudo?
If you use /sudo rest_of_command it should stop giving you the error.
Using sudo can be dangerous so only use it if you feel confident and know what you are doing.

Python: Getting a WindowsError instead of an IOError

I am trying to understand exceptions with Python 2.7.6, on Windows 8.
Here's the code I am testing, which aims to create a new directory at My_New_Dir. If the directory already exists, I want to delete the entire directory and its contents, and then create a fresh directory.
import os
dir = 'My_New_Dir'
try:
os.mkdir(dir)
except IOError as e:
print 'exception thrown'
shutil.rmtree(dir)
os.mkdir(dir)
The thing is, the exception is never thrown. The code works fine if the directory does not already exist, but if the directory does exist, then I get the error:
WindowsError: [Error 183] Cannot create a file when that file already exists: 'My_New_Dir'
But according to the Python documentation for os.mkdir(),
If the directory already exists, OSError is raised.
So why is the Windows error being thrown, rather than the Python exception?
WindowsError is a subclass of OSError. From the exceptions documentation:
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. The errno value maps the winerror value to corresponding errno.h values. This is a subclass of OSError.
You are trying to catch IOError however, which is not such a parent class of WindowsError; as a result it won't suffice to catch either OSError nor WindowsError.
Alter your code to use the correct exception here:
try:
os.mkdir(dir)
except OSError as e:
or use WindowsError; this would tie your code to the Windows platform.
You mis-read it. It is "OSError" not "IOError", and WindowsError is a subclasss of "OSError" for your specific working OS.
>>> issubclass(WindowsError, OSError)
True
Besides, for your propose, this API is better:
os.path.isdir(path): Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.
if os.path.isdir(dir):
shutil.rmtree(dir)
os.mkdir(dir)
If you search for "WindowsError" on the exceptions page, you will see that WindowsError is in fact a Python exception. It is a subclass of OSError, so the documentation is still correct. If you change to
try:
os.mkdir(dir)
except OSError as e:
print 'exception thrown'
shutil.rmtree(dir)
os.mkdir(dir)
then you will catch the exception.

Which Python exception should I throw?

I'm writing some code to manipulate the Windows clipboard. The first thing I do is to try and open the clipboard with OpenClipboard() function from the Windows API:
if OpenClipboard(None):
# Access the clipboard here
else:
# Handle failure
This function can fail. So if it does, I would like to raise an exception. My question is, which of the standard Python exceptions should I raise? I'm thinking WindowsError would be the right one, but not sure. Could someone please give me a suggestion?
It is better to avoid raising standard exceptions directly. Create your own exception class, inherit it from the most appropriate one (WindowsError is ok) and raise it. This way you'll avoid confusion between your own errors and system errors.
Raise the windows error and give it some extra infomation, for example
raise WindowsError("Clipboard can't be opened")
Then when its being debugged they can tell what your windows error means rather than just a random windowserror over nothing.
WindowsError seems a reasonable choice, and it will record extra error information for you. From the docs:
exception WindowsError
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. The errno value maps the winerror value to corresponding errno.h values. ...

Categories