python AttributeError when attempting to save excel chart using PIL - python-imaging-library

I am trying to save an chart from excel into a file, which I want to use later in a powerpoint presentation, but the code I am running keeps on coming up with
"AttributeError: 'NoneType' object has no attribute 'save'" .
Have been looking around google/stackoverflow but none of the suggestions I can find actually help, I keep on getting the error.
The code I am trying is below,
import win32com.client
import PIL
folder_path = r'C:/temp/Monthly_Graphs.xlsm'
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
wb.Sheets('Sheet1').Shapes('Sheet1_Pie_Chart').CopyPicture()
pie_image = PIL.ImageGrab.grabclipboard()
pie_image.savefig(r'C:/temp/pie_test.bmp','BMP')
the traceback is below
Traceback (most recent call last):
File "<ipython-input-12-b8e52c17e4d1>", line 1, in <module>
runfile('C:/python/stackoverflow_1.py', wdir='C:/python')
File "C:\Users\xxxxxxx\AppData\Local\conda\conda\envs\py64bit\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
execfile(filename, namespace)
File "C:\Users\xxxxxxx\AppData\Local\conda\conda\envs\py64bit\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/python/stackoverflow_1.py", line 26, in <module>
pie_image.savefig(r'C:/temp/pie_test.bmp','BMP')
AttributeError: 'NoneType' object has no attribute 'savefig'

Managed to get it to work by referring to the below Q and setting the format of the CopyPicture line. Issue seems to be that excel default copy of the image is not in a format that PIL understands
Python Export Excel Sheet Range as Image
import win32com.client
from PIL import ImageGrab
import win32clipboard as clip
folder_path = r'C:/temp/Monthly_Graphs.xlsm'
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
xlApp = win32com.client.DispatchEx('Excel.Application')
wb = xlApp.Workbooks.Open(folder_path)
wb.Sheets('Sheet1').Shapes('Sheet1_Pie_Chart').CopyPicture(Format=clip.CF_BITMAP)
pie_image = ImageGrab.grabclipboard()
pie_image.save(r'C:/temp/pie_test.bmp','BMP')

Related

PIL.ImageOps.fit() gives AttributeError: 'str' object has no attribute 'size'

i`m getting an error while trying to crop my photo using PIL.ImageOps.fit()
*its
This is my code:
import sys
from PIL import ImageOps, Image, ImageChops
import PIL
#user comand-line input validation
if len(sys.argv) != 3:
sys.exit("Amount of argumets is not corrent")
name, newName = sys.argv[1], sys.argv[2]
splitedName, splitedNewName = name.split("."), newName.split(".")
formats =["jpg","jpeg","png"]
# print(splitedName[1],splitedNewName[1])
if splitedName[1] != splitedNewName[1] and splitedName not in formats:
sys.exit("Formats are not correct!")
#Photo processing
shirt = Image.open("shirt.png")
size = shirt.size
im2 = ImageOps.fit(name,size)
im2.paste(shirt,shirt)
im2.save(newName)
I`m getting an error which says that str doesn`t have attribute size:
Traceback (most recent call last):
File "/home/lev/CS50/shirt/shirt.py", line 26, in <module>
im2 = ImageOps.fit(name,size)
File "/home/lev/miniconda3/lib/python3.9/site-packages/PIL/ImageOps.py", line 461, in fit
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
AttributeError: 'str' object has no attribute 'size'
You are using ImageOps.fit() with as first argument the name of the image (variable name), which is a string. If you look up the documentation of ImageOps.fit(), you see that the first argument should be an image itself, not a filename.
Solution: change this line:
im2 = ImageOps.fit(name,size)
into:
im2 = ImageOps.fit(shirt,size)

Mibian returning "NameError: name 'norm' is not defined..." when using with xlwings

I was trying to write an Excel UDF using xlwings to return finance options calculation from the Mibian library. I've tried the code below.
import xlwings as xw
import mibian
#xw.func
def BSPutOptionImpVol(underlyingPrice,strike,interestRate,expiryDays,premium):
c = mibian.BS([underlyingPrice, strike, interestRate, expiryDays], putPrice=premium)
return c.impliedVolatility
From Excel, I then call the function with the following =BSPutOptionImpVol(45,32,1,127,0.95)
It's returning the following error:
"NameError: name 'norm' is not defined
call = self.underlyingPrice * norm.cdf(self.d1) - \
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 307, in _price
[self.callPrice, self.putPrice] = self._price()
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 276, in init
estimate = eval(className)(args, volatility=mid, performance=True).putPrice
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 29, in impliedVolatility
self.class.name, args, putPrice=self.putPrice)
File ""C:\Users...\anaconda3\lib\site-packages\mibian__init__.py"", line 293, in init
c = mibian.BS([underlyingPrice, strike, interestRate, expiryDays], putPrice=premium)
File ""c:\users...\documents\python scripts\BSPutImVol.py"", line 6, in BSPutOptionImpVol
ret = func(*args)
File ""C:\Users...\anaconda3\lib\site-packages\xlwings\udfs.py"", line 298, in call_udf
res = call_udf(script, fname, args, this_workbook, FromVariant(caller))
File ""C:\Users...\anaconda3\lib\site-packages\xlwings\server.py"", line 195, in CallUDF
return func(args)
File ""C:\Users...\anaconda3\lib\site-packages\win32com\server\policy.py"", line 586, in _invokeex_
return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
File ""C:\Users...\anaconda3\lib\site-packages\win32com\server\policy.py"", line 283, in _invoke_
return self._invoke_(dispid, lcid, wFlags, args)
File ""C:\Users...\anaconda3\lib\site-packages\win32com\server\policy.py"", line 278, in _Invoke_"
I have also tried just calling the function without passing the parameters in (ie the input values are in the python code) but I still get the same error.
However, if I comment out xlwings and just run the Python code from Spyder as below, it works.
#import xlwings as xw
import mibian
##xw.func
def BSPutOptionImpVol(underlyingPrice,strike,interestRate,expiryDays,premium):
c = mibian.BS([underlyingPrice, strike, interestRate, expiryDays], putPrice=premium)
# return c.impliedVolatility
print(c.impliedVolatility)
I'm a newbie to Python, so appreciate any help and advice. Thanks.
Try..
from scipy.stats import norm
Try add
import scipy
to your code. That resolved the 'norm' issue for me.
This worked for me
pip uninstall numpy scipy
and then
pip install -U numpy scipy

PyPDF2.PdfFileReader hangs indefinitely

I'm trying to read this pdf file (https://www.accessdata.fda.gov/cdrh_docs/pdf14/K141693.pdf) and am following these suggestions from SO
Opening pdf urls with pyPdf
I have actually downloaded the file locally and am running the following code
import PyPDF2
pdf_file = open("K141693.pdf")
pdf_read = PyPDF2.PdfFileReader(pdf_file)
but my code hangs indefinitely. I'm running Python 2.7 and here is the stacktrace.
Traceback (most recent call last):
File "", line 1, in
runfile('C:/PoC/pdf_reader.py', wdir='C:/PoC')
File
"C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 880, in runfile
execfile(filename, namespace)
File
"C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
line 87, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/PoC/pdf_reader.py", line 13, in
pdf_read = PyPDF2.PdfFileReader(pdf_file)
File "C:\ProgramData\Anaconda2\lib\site-packages\PyPDF2\pdf.py",
line 1084, in init
self.read(stream)
File "C:\ProgramData\Anaconda2\lib\site-packages\PyPDF2\pdf.py",
line 1697, in read
line = self.readNextEndLine(stream)
File "C:\ProgramData\Anaconda2\lib\site-packages\PyPDF2\pdf.py",
line 1938, in readNextEndLine
x = stream.read(1)
KeyboardInterrupt
I came across another post here PyPDF2 hangs on processing but that too doesn't have a response.
You need to parse the file in binary ('rb') mode. (This works in Python 3:)
import PyPDF2
pdf_file = open("K141693.pdf", "rb")
read_pdf = PyPDF2.PdfFileReader(pdf_file)

TensorFlow: use gfile.FastGfile() method can't not read a file with its path include Chinese characters

I want to read use gfile.FastGFile(image_path, 'rb').read() to read a picture and use it as the input of my project, and I use the directory name as the lable of these pictures which are include in the directory, when the directory name is in English, my code works fine, but when the directory name is in Chinese, it throws this Error:
Traceback (most recent call last):
File "F:/pythonWS/imageFilter/jpegFileJudge.py", line 27, in <module>
image_data = gfile.FastGFile(image_path, 'rb').read()
File "C:\Program Files\Python35\lib\site-
packages\tensorflow\python\lib\io\file_io.py", line 106, in read
self._preread_check()
File "C:\Program Files\Python35\lib\site-
packages\tensorflow\python\lib\io\file_io.py", line 73, in _preread_check
compat.as_bytes(self.__name), 1024 * 512, status)
File "C:\Program Files\Python35\lib\contextlib.py", line 66, in __exit__
next(self.gen)
File "C:\Program Files\Python35\lib\site-
packages\tensorflow\python\framework\errors_impl.py", line 466, in
raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile
failed to Create/Open: F:\vsWorkspace\pics\test\三宝鸟
\0ff41bd5ad6eddc403fa02d13bdbb6fd526633fe.jpg :
ϵͳ\udcd5Ҳ\udcbb\udcb5\udcbdָ\udcb6\udca8\udcb5\udcc4\udcceļ\udcfe\udca1\udca3
my test code is :
# -*- coding: utf-8 -*-
import glob
import os
import random
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
image_folder='F:/vsWorkspace/pics/test'
os.chdir(image_folder)
count=0
for each in os.listdir(image_folder):
each=os.path.abspath(each)
os.chdir(each)
for image_path in os.listdir(each):
image_path = os.path.abspath(image_path)
print(image_path)
image_data = gfile.FastGFile(image_path, 'rb').read()
count += 1
os.chdir(image_folder)
My envirorment is Windows7 x64, python 3.5.3 and TensorFlow 1.0, How can I solve this problem?
By the way,I have to use Chinese directories' name use my pictures lables.

using boto3 in a python3 virtual env in AWS Lambda

I am trying to use Python3.4 and boto3 to walk an S3 bucket and publish some file locations to an RDS instance. The part of this effort I am having trouble with is when using boto3. My lambda function looks like the following:
import subprocess
def lambda_handler(event, context):
args = ("venv/bin/python3.4", "run.py")
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read()
print(output)
and, in my run.py file I have some lines:
import boto3
s3c = boto3.client('s3')
which cause an exception. The run.py file is not relevant for this question however, so in order make this post more concise, I've found that the cause of this error is generated with executing the lambda function:
import subprocess
def lambda_handler(event, context):
args = ("python3.4", "-c", "import boto3; print(boto3.client('s3'))")
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read()
print(output)
My logstream reports the error:
Event Data
START RequestId: 2b65421a-664d-11e6-81db-974c7c09d283 Version: $LATEST
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/var/runtime/boto3/__init__.py", line 79, in client
return _get_default_session().client(*args, **kwargs)
File "/var/runtime/boto3/session.py", line 250, in client
aws_session_token=aws_session_token, config=config)
File "/var/runtime/botocore/session.py", line 818, in create_client
client_config=config, api_version=api_version)
File "/var/runtime/botocore/client.py", line 63, in create_client
cls = self._create_client_class(service_name, service_model)
File "/var/runtime/botocore/client.py", line 85, in _create_client_class
base_classes=bases)
File "/var/runtime/botocore/hooks.py", line 227, in emit
return self._emit(event_name, kwargs)
File "/var/runtime/botocore/hooks.py", line 210, in _emit
response = handler(**kwargs)
File "/var/runtime/boto3/utils.py", line 61, in _handler
module = import_module(module)
File "/var/runtime/boto3/utils.py", line 52, in import_module
__import__(name)
File "/var/runtime/boto3/s3/inject.py", line 13, in <module>
from boto3.s3.transfer import S3Transfer
File "/var/runtime/boto3/s3/transfer.py", line 135, in <module>
from concurrent import futures
File "/var/runtime/concurrent/futures/__init__.py", line 8, in <module>
from concurrent.futures._base import (FIRST_COMPLETED,
File "/var/runtime/concurrent/futures/_base.py", line 357
raise type(self._exception), self._exception, self._traceback
^
SyntaxError: invalid syntax
END RequestId: 2b65421a-664d-11e6-81db-974c7c09d283
REPORT RequestId: 2b65421a-664d-11e6-81db-974c7c09d283 Duration: 2673.45 ms Billed Duration: 2700 ms Memory Size: 1024 MB Max Memory Used: 61 MB
I need to use boto3 downstream of run.py. Any ideas on how to resolve this are much appreciated. Thanks!