Can't pickle <class 'pywintypes.datetime'>: attribute lookup datetime on pywintypes failed - python-3.5

I am using python 3.5 (32bit), win10-64bit, OpenOPC, and I have downloaded pywin32 build 64bit. I have run the following python code:
import OpenOPC
import time
opc=OpenOPC.client()
opc.connect('Matrikon.OPC.Simulation.1')
tags =['Random.Int4','Random.Real4']
while True:
try:
value = opc.read(tags,group='Group0',update=1)
print (value)
except OpenOPC.TimeoutError:
print ("TimeoutError occured")
time.sleep(5)
but I always get this error message:
Traceback (most recent call last): File "C:\Program Files
(x86)\Python35-32\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj) File "C:\Program Files (x86)\Python35-32\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle : attribute lookup datetime on pywintypes failed.

I have found a solution:
import OpenOPC
import time
import pywintypes
pywintypes.datetime = pywintypes.TimeType
opc=OpenOPC.client()
opc.servers()
opc.connect('Matrikon.OPC.Simulation.1')
tags =['Random.Int1','Random.Real4','Random.Int2','Random.Real8']
while True:
try:
value = opc.read(tags,group='Group0',update=1)
print (value)
except OpenOPC.TimeoutError:
print ("TimeoutError occured")
time.sleep(1)

Related

Python can properly be executed in IDEA, but when executing the executable file, following error appears: ModuleNotFoundError: No module named 'PIL'

I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Here is my code:
import shutil
from PIL import Image
import glob, os
import time
output_directory = "./Output"
def photo_picker():
pictures = []
try:
for filename in glob.iglob("./Input/*.jpg"):
pictures.append(filename)
except FileNotFoundError:
print("could not execute")
return pictures
def create_output_folder():
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
try:
os.mkdir(path=output_directory, mode=777)
except FileExistsError:
print("Could not execute")
def crop_image(img, new_name):
size = (2000, 2000)
with Image.open(img) as im:
im.thumbnail(size)
print(im.info)
img_name = f"{new_name}"
im.save(output_directory + "/" + img_name, "JPEG")
def main():
photos = photo_picker()
create_output_folder()
time.sleep(2)
for f in photos:
img_name_splitted = f.split("/")
img_name = img_name_splitted[len(img_name_splitted) - 1]
print(img_name)
crop_image(f, img_name)
return 0
if __name__ == "__main__":
main()
I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.

TypeError: <class 'str'> is not callable-Scrapy Framework

I am trying to run some codes from 'Learning Scrapy' book and ran into some errors. The codes that I ran:
`
import scrapy
from ..items import PropertiesItem
from scrapy.loader import ItemLoader
from itemloaders.processors import MapCompose, Join
from urllib.parse import urlparse
class BasicSpider(scrapy.Spider):
name = "basic"
allowed_domains = ["web"]
start_urls = (
'http://localhost:9312/properties/property_000000.html',
)
def parse(self, response):
l = ItemLoader(item=PropertiesItem(), response=response)
l.add_xpath('title', '//*[#itemprop="name"][1]/text()', MapCompose(str.strip, str.title))
l.add_xpath('price', './/*[#itemprop="price"][1]/text()', MapCompose(lambda i: i.replace(',', ''), float), re='[,.0-9]+')
l.add_xpath('description', '//*[#itemprop="description"][1]/text()', MapCompose(str.strip), Join())
l.add_xpath('address', '//*[#itemtype="http://schema.org/Place"][1]/text()', MapCompose(str.strip))
l.add_xpath('image_urls', '//*[#itemprop="image"][1]/#src', MapCompose(lambda i: urlparse.urljoin(response.url, i)))
return l.load_item()
`
And the error I got:
`
Traceback (most recent call last):
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\twisted\internet\defer.py", line 857, in _runCallbacks
current.result = callback( # type: ignore[misc]
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\scrapy\spiders\__init__.py", line 67, in _parse
return self.parse(response, **kwargs)
File "C:\Users\Sadat\Desktop\scrapybook\properties\properties\spiders\basic.py", line 23, in parse
l.add_xpath('image_urls', '//*[#itemprop="image"][1]/#src', 'image_urls', '//*[#itemprop="image"][1]/#src',MapCompose(lambda i: urlparse.urljoin(response.url, i)))
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\itemloaders\__init__.py", line 350, in add_xpath
self.add_value(field_name, values, *processors, **kw)
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\itemloaders\__init__.py", line 183, in add_value
value = self.get_value(value, *processors, **kw)
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\itemloaders\__init__.py", line 246, in get_value
proc = wrap_loader_context(proc, self.context)
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\itemloaders\common.py", line 11, in wrap_loader_context
if 'loader_context' in get_func_args(function):
File "c:\users\sadat\appdata\local\programs\python\python39\lib\site-packages\itemloaders\utils.py", line 53, in get_func_args
raise TypeError('%s is not callable' % type(func))
TypeError: <class 'str'> is not callable
2022-11-02 16:04:47 [scrapy.core.engine] INFO: Closing spider (finished)
`
Specifically, the code that was giving error initially was this snippet: MapCompose(unicode.strip, unicode.title), there are multiples of them. After some digging, I found out that in later versions of python, str is used instead of unicode. But even after using str I am getting this error. I need help solving this error. Thanks.
Please note that I am using:
Python 3.9.4
Scrapy 2.6.1
VS Code 1.72
I was expecting scrapy to provide a clean scraped data via the Items, not this error.

Python3 StringIO has no clone

Following code works in Python2 but not in Python3?
import http.client
from io import StringIO
if __name__ == '__main__':
res=http.client.HTTPMessage(StringIO(u"headers"))
print(str(res))
[]$ python3 test.py
Traceback (most recent call last):
File "test.py", line 9, in <module>
print(str(res))
File "/usr/lib64/python3.9/email/message.py", line 135, in __str__
return self.as_string()
File "/usr/lib64/python3.9/email/message.py", line 158, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib64/python3.9/email/generator.py", line 97, in flatten
policy = policy.clone(max_line_length=self.maxheaderlen)
AttributeError: '_io.StringIO' object has no attribute 'clone'
I'm currently porting old Python2 code over to Python3.
This is a dummy test of a problem I run into.

Pytest stop runnig with AttributeError (module 'html' has no attribute 'td' in pytest-html)

In my PyTest, I have included conftest.py for customizing the HTML report.
But I have the following error comes up while the test script tries to access the HTML report.
"C:\Users\gobiraaj.anandavel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pluggy\callers.py", line 187, in _multicall
INTERNALERROR> res = hook_impl.function(*args)
INTERNALERROR> File "C:\Projects\TripTickAT\conftest.py", line 14, in pytest_html_results_table_row
INTERNALERROR> cells.insert(2, html.td(report.status_code))
INTERNALERROR> AttributeError: module 'html' has no attribute 'td'
Traceback (most recent call last):
File "C:\Users\gobiraaj.anandavel\AppData\Local\Programs\Python\Python37-32\Scripts\pytest-script.py", line 11, in <module>
load_entry_point('pytest==5.2.2', 'console_scripts', 'pytest')()
File "C:\Users\gobiraaj.anandavel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytest-5.2.2-py3.7.egg\_pytest\config\__init__.py", line
File "C:\Projects\TripTickAT\conftest.py", line 8, in pytest_html_results_table_header
cells.insert(2, html.th('Status_code'))
AttributeError: module 'html' has no attribute 'th'
conftest.py
from datetime import datetime
import html.parser
import pytest
#pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
cells.insert(2, html.th('Status_code'))
cells.insert(1, html.th('Time', class_='sortable time', col='time'))
cells.pop()
#pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
cells.insert(2, html.td(report.status_code))
cells.insert(1, html.td(datetime.utcnow(), class_='col-time'))
cells.pop()
#pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
Use the following html import instead
from py.xml import html
Initially pycharm will not identify this import but this will not impact the execution. If you want you can change the pycharm settings to ignore this error

ImportError: No module named url

when i run the the given code in prepare_dataset.py whose code is below as
from urllib.request
import urlopen
import json as simplejson
def main():
# Download and prepare datasets
list_generator = video_list_generator.Generator("playlists.json", youtube_api_client.Client("AIzaSyD_UC-FpXbJeWzPfscLz9RhqSjKwj33q6A"))
video_list = list_generator.get_video_list("piano")
downloader = youtube_video_downloader.Downloader()
downloader.download_from_list(video_list)
if __name__ == '__main__':
main()
as python prepare_dataset.py in command-line then i get these errors
Traceback (most recent call last):
File "prepare_dataset.py", line 1, in <module>
from urllib.request import urlopen
ImportError: No module named request
How can i get to run the above file any idea guys?

Resources