Now pyPDF2 support encryption, according to this answer, it may be implemented like this:
import os
import PyPDF2
from PyPDF2 import PdfFileReader
fp = open(filename)
pdfFile = PdfFileReader(fp)
password = "mypassword"
if pdfFile.isEncrypted:
try:
pdfFile.decrypt(password)
print('File Decrypted (PyPDF2)')
except:
command = ("cp "+ filename +
" temp.pdf; qpdf --password='' --decrypt temp.pdf " + filename
+ "; rm temp.pdf")
os.system(command)
print('File Decrypted (qpdf)')
fp = open(filename)
pdfFile = PdfFileReader(fp)
else:
print('File Not Encrypted')
Note that this code, use pyPDF2 by default and failback to qpdf in case of issue.