I can't save a list - python-3.x

import tkinter as tk
list = []
def add():
element = entry.get()
entry.delete(0, 1000)
list.append(element)
def save():
with open("save.txt", "w") as f:
for element in list:
f.write(element + ",")
root = tk.Tk()
frameList = tk.Frame(root)
frameList.pack()
entry = tk.Entry(root)
entry.pack()
btnAdd = tk.Button(root, text="add", command=add)
btnAdd.pack(pady=5)
btnSave = tk.Button(root, text="save", command=save)
btnSave.pack()
root.mainloop()
this code give me this error when I save:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/HP/Desktop/python/github/write.py", line 11, in save
with open("save.txt", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'save.txt'
and if I create the file "save.txt" it says:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/HP/Desktop/python/github/write.py", line 13, in save
f.write(element + ",")
OSError: [Errno 9] Bad file descriptor
please, can you help me to solve this problem?
sorry for this last sentence but I have to add some "not code" to publish the question, so I will say some random stuff from now, sorry

Related

name error while trying to refering the "view " method in same class

class Solution:
def bottomView(self, root):
# code here
v={0:root}
self.View(root,v,0)
return [ d for i,d in v.items()]
def View(self,root,v,d):
v[d]=root.data
if root.left:
view(self,root.left,v,d-1)
if root.right:
view(self,root.right,v,d+1)
//error
Traceback (most recent call last):
File "/home/f94469e221bb681a04f81ecf69c00640.py", line 103, in
res = ob.bottomView(root)
File "/home/f94469e221bb681a04f81ecf69c00640.py", line 7, in bottomView
self.View(root,v,0)
File "/home/f94469e221bb681a04f81ecf69c00640.py", line 12, in View
view(self,root.left,v,d-1)
NameError: name 'view' is not defined

Ttk style layout not found how to fix?

I am making my own custom Menubar.My work is in process but i recently came across one confusion.
Here is my code:-
from tkinter import *
from tkinter.ttk import Style,Frame as fp
class menu():
def __init__(self,parent,bg="#ffffcc"):
self.parent = parent
self.bg = bg
#this is a image in base 64 encoded format
borderImageData='''
iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAABmJLR0QA/wD/
AP+gvaeTAAACZ0lEQVRoge2aPU/TURSHn/MvpbYYKa9qQQnlTSOJRBzoYBDi
YEwcdPFD+PIFHHRxcCXxO7gxmBgXSTcxMYQEE4spoEWIvBcDBfp2HVqlxRhK
TDwtuc947vJ7cnPvGc6R/v5+KhlHO8C/YgW0sQLaWAFtqg4WxKEjJMGQaQyK
txbHpZGqmGzG7GzKyoyZfcfsOCZbeChFjaz+vAw/oq6V1K75HiERJ5v+33H/
xKnC55czF3CfYD1mxkbY+Pb7sECguUtuPQbMh5d8eksmpZL2r7jccvEGV++B
Ma+fsRzNlwOBAID3lNx+gjHm1VNiEweuqSwwWZajxCak85oEQ3wOk0my/4j7
7uD1m7ERNuY1Ux7KeozwC3x+uXI3V3AAXFXSPcjCFAtTmuFKw8xPsviRrsHc
B+MANHVS7WPuvXK0kjGz43hqaOogL3CyASC+oJrqKMQXAWoayQmI2wuY1J5q
qKOQ2gXE4+MYdGIroI0V0MYKaGMFtLEC2lgBbayANlZAGyugjRXQxgpoYwW0
sQLaWAFtrIA2DmCSCQC3RzlL6VR7AZIJ8jewtQaIv0Uz05GoPQuYrVXyAqsz
JBO0D+imKh0JhtjbYmWGvEAmbabDtPTSelk5Wimc6yNwiekw2Qz7j3hylERc
hh9S36YZ7jCkoU2GHpjtdTM5mqv8mtSnkyxFpHtQeoZIJ1n7UnbDelc1vTfl
+n1EePOcH0u5cvGyR11r/hJSeyxFzPZGmSx7SE09p3twe1j7asZGCifCcnDt
UhzaBwgOSHMnZbNuw86mWY7K3Lg5ZN2mAjkWnbiisQLaWAFtKl7gJzIjtMOb
uqQwAAAAAElFTkSuQmCC
'''
self.borderImage = PhotoImage( data=borderImageData,master=self.parent)
self.TP_style=Style()
self.TP_style.element_create("RoundedFrame",
"image", self.borderImage,
border=14, sticky="nsew")
self.TP_style.layout("RoundedFrame",
[("RoundedFrame", {"sticky": "nsew"})])
self.frame_one = fp(parent, style="RoundedFrame", padding=10,width=100,height=100)
self.frame_one.pack()
l1=Label(parent,image=self.borderImage).pack()
def popup(self,x,y,width=110,height=120):
self.width=width
self.height=height
self.app = Tk()
self.app.config(bg=self.bg)
self.app.geometry(f"{self.width}x{self.height}+{x}+{y}")
self.app.wm_attributes("-topmost",True)
self.app.overrideredirect(True)
self.app.focus_force()
#self.frame_one = fp(self.app, style="RoundedFrame", padding=10,width=100,height=100)
#self.frame_one.pack()
#l1=Label(self.app,image=self.borderImage).pack()
#self.m.pack_propagate(0)
def destroy(event):
self.app.destroy()
self.app.bind("<FocusOut>",destroy)
if __name__ == "__main__":
root = Tk()
menu = menu(root)
def evt(evt):
menu.popup(evt.x_root,evt.y_root,width=200,height=400)
root.bind("<Button-3>",evt)
root.mainloop()
If i write style for frame like
self.frame_one = fp(parent, style="RoundedFrame", padding=10,width=100,height=100)
in the init() method every thing works fine. If same thing i write in popup methon(where i have just commented out),i got the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\mishra\P_Menu.py", line 64, in evt
menu.popup(evt.x_root,evt.y_root,width=200,height=400)
File "C:\Users\mishra\P_Menu.py", line 51, in popup
self.frame_one = fp(self.app, style="RoundedFrame", padding=10,width=100,height=100)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\ttk.py", line 740, in __init__
Widget.__init__(self, master, "ttk::frame", kw)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\ttk.py", line 557, in __init__
tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: Layout RoundedFrame not found
Same thing for Lable
l1=Label(self.app,image=self.borderImage).pack()
In the init() section everything works fine but in popup method I got following error.
Traceback (most recent call last):
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\mishra\P_Menu.py", line 64, in evt
menu.popup(evt.x_root,evt.y_root,width=200,height=400)
File "C:\Users\mishra\P_Menu.py", line 53, in popup
l1=Label(self.app,image=self.borderImage).pack()
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: image "pyimage1" doesn't exist
I want to know how to fix it,cause i want to know logic behind it and use in popup() method.
Any help will be appriciated.
Thank You!
Maybe it's because popup creates a new Tk instance as self.app, but the style belongs to the first Tk instance created by root = Tk(). So a child of the second Tk instance cannot recognize it. Maybe you can try changing self.app = Tk() to self.app = Toplevel() to see if it works?

Python3 multiprocessing shared dictionary consume by all process

I'm beginner for multiprocessing,
i would like to use multiprocessing for parallel code running with streaming data.
To start good, I have coded below and got error.
Could you please tell me correct way to print on the screen.
Code:
import sys
from multiprocessing import Process, Manager
import time
def producer(dic, name):
for i in range(10000):
dic["A"] = i
time.sleep(2)
def consumer(dic, name):
for i in range(10000):
aval = dic.get("A")
#print(f" {name} - Val = {aval}")
sys.stdout.write(f" {name} - Val = {aval}")
sys.stdout.flush()
time.sleep(2.2)
if __name__ == '__main__':
manager = Manager()
dic = manager.dict()
Process(target=producer, args=(dic,"TT")).start()
time.sleep(1)
Process(target=consumer, args=(dic,"Con1")).start()
Process(target=consumer, args=(dic,"Con2")).start()
When I run the same in the windows console, I got below error, how can I print Consumer's print function in the console.Thanks
(base) PS D:\> python .\mulpro.py
Process Process-3:
Process Process-4:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 811, in
_callmethod
conn = self._tls.connection
AttributeError: 'ForkAwareLocal' object has no attribute 'connection'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 297, in _
bootstrap
self.run()
File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 99, in ru
n
self._target(*self._args, **self._kwargs)
File "D:\mulpro.py", line 19, in consumer
aval = dic.get("A")
File "<string>", line 2, in get
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 815, in
_callmethod
self._connect()
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 802, in
_connect
conn = self._Client(self._token.address, authkey=self._authkey)
File "C:\ProgramData\Anaconda3\lib\multiprocessing\connection.py", line 490, i
n Client
c = PipeClient(address)
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\multiprocessing\connection.py", line 691, i
n PipeClient
_winapi.WaitNamedPipe(address, 1000)
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 811, in
_callmethod
conn = self._tls.connection
FileNotFoundError: [WinError 2] The system cannot find the file specified
AttributeError: 'ForkAwareLocal' object has no attribute 'connection'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 297, in _
bootstrap
self.run()
File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 99, in ru
n
self._target(*self._args, **self._kwargs)
File "D:\mulpro.py", line 19, in consumer
aval = dic.get("A")
File "<string>", line 2, in get
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 815, in
_callmethod
self._connect()
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 802, in
_connect
conn = self._Client(self._token.address, authkey=self._authkey)
File "C:\ProgramData\Anaconda3\lib\multiprocessing\connection.py", line 490, i
n Client
c = PipeClient(address)
File "C:\ProgramData\Anaconda3\lib\multiprocessing\connection.py", line 691, i
n PipeClient
_winapi.WaitNamedPipe(address, 1000)
FileNotFoundError: [WinError 2] The system cannot find the file specified
Process Process-2:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 297, in _
bootstrap
self.run()
File "C:\ProgramData\Anaconda3\lib\multiprocessing\process.py", line 99, in ru
n
self._target(*self._args, **self._kwargs)
File "D:\mulpro.py", line 13, in producer
dic["A"] = i
File "<string>", line 2, in __setitem__
File "C:\ProgramData\Anaconda3\lib\multiprocessing\managers.py", line 818, in
_callmethod
conn.send((self._id, methodname, args, kwds))
File "C:\ProgramData\Anaconda3\lib\multiprocessing\connection.py", line 206, i
n send
self._send_bytes(_ForkingPickler.dumps(obj))
File "C:\ProgramData\Anaconda3\lib\multiprocessing\connection.py", line 280, i
n _send_bytes
ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
BrokenPipeError: [WinError 232] The pipe is being closed
The reason might be that the main process doesn't wait for two children process, so make your code like this could work:
def run():
manager = Manager()
dic = manager.dict()
Process(target=producer, args=(dic,"TT")).start()
time.sleep(1)
Process(target=consumer, args=(dic,"Con1")).start()
Process(target=consumer, args=(dic,"Con2")).start()
while True:
pass
if __name__ == '__main__':
run()
However it's very strange that if I append a dead loop in main instead of using another function, it still raise that exception. Anyway, the code above could help.

Python 3 multiprocessing error

I'm trying to run this code taken form python doc
https://docs.python.org/3.6/library/multiprocessing.html
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
but here what I get:
main line
module name: __main__
parent process: 15744
process id: 7344
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
run_name="__mp_main__")
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 261, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 231, in _get_code_from_file
with open(fname, "rb") as f:
OSError: [Errno 22] Invalid argument: 'C:\\Users\\SomeUser\\<stdin>'
what am I doing wrong? I use python 3.6.1.

Scrapy not calling the assigned pipeline when run from a script

I have a piece of code to test scrapy. My goal is to use scrapy without having to call the scrapy command from the terminal, so I can embed this code somewhere else.
The code is the following:
from scrapy import Spider
from scrapy.selector import Selector
from scrapy.item import Item, Field
from scrapy.crawler import CrawlerProcess
import json
class JsonWriterPipeline(object):
file = None
def open_spider(self, spider):
self.file = open('items.json', 'wb')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
class StackItem(Item):
title = Field()
url = Field()
class StackSpider(Spider):
name = "stack"
allowed_domains = ["stackoverflow.com"]
start_urls = ["http://stackoverflow.com/questions?pagesize=50&sort=newest"]
def parse(self, response):
questions = Selector(response).xpath('//div[#class="summary"]/h3')
for question in questions:
item = StackItem()
item['title'] = question.xpath('a[#class="question-hyperlink"]/text()').extract()[0]
item['url'] = question.xpath('a[#class="question-hyperlink"]/#href').extract()[0]
yield item
if __name__ == '__main__':
settings = dict()
settings['USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
settings['ITEM_PIPELINES'] = {'JsonWriterPipeline': 1}
process = CrawlerProcess(settings=settings)
spider = StackSpider()
process.crawl(spider)
process.start()
As you see, the code is self contained and I override two settings; the USER_AGENT and the ITEM_PIPELINES. However when I set debug points in the JsonWriterPipeline class, I see that the code is executed and the debug points are never reached, thus the custom pipeline is not being used.
How can this be fixed?
I get 2 errors when running your script with scrapy 1.3.2 and Python 3.5.
First:
Unhandled error in Deferred:
2017-02-21 13:47:23 [twisted] CRITICAL: Unhandled error in Deferred:
2017-02-21 13:47:23 [twisted] CRITICAL:
Traceback (most recent call last):
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/utils/misc.py", line 39, in load_object
dot = path.rindex('.')
ValueError: substring not found
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/twisted/internet/defer.py", line 1301, in _inlineCallbacks
result = g.send(result)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/crawler.py", line 72, in crawl
self.engine = self._create_engine()
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/crawler.py", line 97, in _create_engine
return ExecutionEngine(self, lambda _: self.stop())
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/core/engine.py", line 70, in __init__
self.scraper = Scraper(crawler)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/core/scraper.py", line 71, in __init__
self.itemproc = itemproc_cls.from_crawler(crawler)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/middleware.py", line 58, in from_crawler
return cls.from_settings(crawler.settings, crawler)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/middleware.py", line 34, in from_settings
mwcls = load_object(clspath)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/utils/misc.py", line 41, in load_object
raise ValueError("Error loading object '%s': not a full path" % path)
ValueError: Error loading object 'JsonWriterPipeline': not a full path
You need to give a complete path for the pipeline. For example here, the __main__ namespace works:
settings['ITEM_PIPELINES'] = {'__main__.JsonWriterPipeline': 1}
Second (with this pipeline class fix above), you get loads of:
2017-02-21 13:47:52 [scrapy.core.scraper] ERROR: Error processing {'title': 'Apply Remote Commits to a Local Pull Request',
'url': '/questions/42367647/apply-remote-commits-to-a-local-pull-request'}
Traceback (most recent call last):
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "test.py", line 20, in process_item
self.file.write(line)
TypeError: a bytes-like object is required, not 'str'
which you can fix with writing items JSON as bytes:
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line.encode('ascii'))
return item

Resources