Python ConfigParser.write() missing 1 required positional argument 'fp'? - python-3.x

Code here (left out the unrelated Kivy stuff):
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from configparser import ConfigParser
import os
class MIDIApp(App):
def build(self):
self.config = ConfigParser()
self.config.read('values.ini')
Window.size = Window.size
return MainWindow()
def input1_comp_move(self, value):
print(int(value))
def input1_save_comp_value(self, value):
self.config['Input1']['comp'] = str(value)
print(str(value))
with open('values.ini', 'w') as config_file:
ConfigParser.write(config_file)
print('Input1 comp value is ', value)
class MainWindow(Widget):
pass
if __name__ == '__main__':
MIDIApp().run()
When I run this I get the error ConfigParser.write(self.config_file)
TypeError: write() missing 1 required positional argument: 'fp'
And when I debug by leaving it blank it requires 2 positional arguments 'self' and 'filename', it didn't require that when I tried to used this another program. What am I missing?

It should be self.config.write(self.config_file) or, if you insist, ConfigParser.write(self.config, self.config_file).
Thanks ForceBru

Related

Author's code works but mine doesn't [Kivy]

I'm learning from a book about making apps with Kivy and there's this block of code:
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class TestApp(App):
press_count = 1
def button_press(self, button_pressed):
print('Button Pressed', TestApp.press_count, 'TImes')
TestApp.press_count += 1
def build(self):
my_btn = Button(text='Click Me')
my_btn.bind(on_press=TestApp.button_press)
textinput = TextInput(text='Data Inside TextInput')
box_layout = BoxLayout(orientation='vertical')
box_layout.add_widget(widget=my_btn)
box_layout.add_widget(widget=textinput)
return box_layout
if __name__ == '__main__':
TestApp().run()
when I run this I get understandably TypeError: button_press() missing 1 required positional argument: 'button_pressed' my question is why the author of the book isn't getting this error and the code runs ?
my_btn.bind(on_press=TestApp.button_press)
This is wrong, it should be my_btn.bind(on_press=self.button_press).

Access to an instanced class from an other script run by first

I'm trying to access to an instanced class build by firstscript.py from secondscript.py.
I run secondscript.py from firstscript.py by os.system('sudo secondscript.py') and I want access to the namespace of firstscript.py. For example I have the following code:
# firstscript.py
import wx
import abcd
class MyFrame(abcd):
def __init__(self, *args, **kwds):
abcd.__init__(self, *args, **kwds)
def log(self,str_log):
self.text_ctrl_logging.SetForegroundColour(wx.BLACK)
self.text_ctrl_logging.AppendText(str_log+'\n')
def runsudo(self):
os.system('sudo ./secondscript.py')
class fghi(wx.App):
def OnInit(self):
self.frame = MyFrame(None, wx.ID_ANY, "")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
if __name__ == "__main__":
app = fghi(0)
app.MainLoop()
and the following is the secondscript.py
from firstscript import MyFrame
MyFrame.log("HELLO")
From secondscript.py I want print some string on text_ctrl_logging by log method.
But the following is the error:
TypeError: log() missing 1 required positional argument: 'str_log'
I'm sorry I'm a newbie then be patient for the stupid question.

Type Error: unsupported operand type(s) for /: 'Nonetype' and 'int'

from pytube import YouTube
from tkinter import filedialog
from tkinter import ttk
from tkinter import*
import threading
import re
class Application:
def __init__(self,root):
self.root=root
self.root.grid_rowconfigure(0,weight=2)
self.root.grid_columnconfigure(0,weight=1)
self.root.config(bg="#ffdddd")
top_label=Label(self.root,text="YouTube download manager",fg="blue",font=("ALGERIAN",70))
top_label.grid(pady=(0,10))
link_label=Label(self.root,text="Please paste your YouTube video link",bg="black",fg="red",font=("Agency FB",30))
link_label.grid(pady=(0,20))
self.YoutubeEntryVar=StringVar()
self.YoutubeEntry=Entry(self.root,width=70,textvariable=self.YoutubeEntryVar,font=("Lucida Console",25),fg="blue")
self.YoutubeEntry.grid(pady=(0,20),ipady=5)
self.YoutubeEntryError=Label(self.root,text="",font=("Colonna MT",20),fg="green")
self.YoutubeEntryError.grid(pady=(0,8))
self.YoutubeFileSave=Label(self.root,text="Choose Directory",font=("Agency FB",20),fg="black")
self.YoutubeFileSave.grid(pady=(0,8))
self.YoutubeButton=Button(self.root,text="Directory",font=("Colonna MT",20),command=self.FileDirectory)
self.YoutubeButton.grid(pady=(10,3),ipady=5)
self.FileLocation=Label(self.root,text="",font=("Harlow Solid Italic",20))
self.FileLocation.grid()
self.DownloadSelect=Label(self.root,text="Choose the format to download",font=("Century Gothic",20))
self.DownloadSelect.grid()
self.DownloadChoice=[("Audio MP3",1),("Video MP4",2)]
self.Choice=StringVar()
self.Choice.set(1)
for text,mode in self.DownloadChoice:
self.YoutubeChoice=Radiobutton(self.root,text=text,font=("Candara",10),variable=self.Choice,value=mode)
self.YoutubeChoice.grid()
self.DownloadButton=Button(self.root,text="Download",font=("Lucida Console",10),command=self.checkLink)
self.DownloadButton.grid(pady=(5,5))
def checkLink(self):
self.youtubeMatch=re.match("https://www.youtube.com/",self.YoutubeEntryVar.get())
if(not self.youtubeMatch):
self.YoutubeEntryError.config(text="Please choose a valid YouTube link !!")
elif(not self.FolderName):
self.FileLocation.config(text="Please choose a directory !!",fg="red")
elif(self.youtubeMatch and self.FolderName):
self.downloadFile()
def downloadFile(self):
self.newWindow=Toplevel(self.root)
self.root.withdraw()
self.newWindow.state("zoomed")
self.newWindow.grid_rowconfigure(0,weight=2)
self.newWindow.grid_columnconfigure(0,weight=1)
self.app=Second(self.newWindow,self.YoutubeEntryVar.get(),self.FolderName,self.Choice.get())
def FileDirectory(self):
self.FolderName=filedialog.askdirectory()
if(len(self.FolderName)>0):
self.FileLocation.config(text=self.FolderName,fg="green")
return True
else:
self.FileLocation.config(text="Please choose a directory !!",fg="red")
class Second:
def __init__(self,downloadWindow,youtubeLink,foldername,FileChoice):
self.downloadWindow=downloadWindow
self.youtubeLink=youtubeLink
self.foldername=foldername
self.FileChoice=FileChoice
self.yt=YouTube(self.youtubeLink)
if(FileChoice=='1'):
self.videoType=self.yt.streams.filter(only_audio=True).first()
self.MaxfileSize=self.videoType.filesize
if(FileChoice=='2'):
self.videoType=self.yt.streams.first()
self.MaxfileSize=self.videoType.filesize
self.Loading=Label(self.downloadWindow,text="Download in Progress.........",font=("Agency FB",40))
self.Loading.grid()
self.percent=Label(self.downloadWindow,text="0",font=("Agency FB",20))
self.percent.grid()
self.progressBar=ttk.Progressbar(self.downloadWindow,length=500,orient='horizontal',mode='indeterminate')
self.progressBar.grid(pady=(50,0))
self.progressBar.start()
threading.Thread(target=self.yt.register_on_progress_callback(self.show_Pregress)).start()
threading.Thread(target=self.downloadfile).start()
def downloadfile(self):
if(self.FileChoice=='1'):
self.yt.streams.filter(only_audio=True).first().download(self.foldername)
if(self.FileChoice=='2'):
self.yt.streams.filter().first().download(self.foldername)
def show_Pregress(self,streams=None,Chunks=None,filehandle=None,bytes_remaining=None):
percentCount = float("%0.2f"% (100 - (100*(bytes_remaining/self.MaxfileSize))))
if(percentCount<100):
self.percent.config(text=str(percentCount))
else:
self.progressBar.stop()
self.Loading.forget()
self.progressBar.forget()
self.downloadfinished=Label(self.downloadWindow,text="Download Finished",font=("ALGERIAN",20))
self.downloadfinished.grid(pady(150,0))
self.downloadfile=Label(self.downloadWindow,text=self.yt.title,font=("ALGERIAN",20))
self.downloadfile.grid(pady(50,0))
if __name__=="__main__":
window=Tk()
window.title("YouTube Download Manager")
window.state("zoomed")
app=Application(window)
mainloop()
Most probably your function:
def show_Pregress(self,streams=None,Chunks=None,filehandle=None,bytes_remaining=None):
percentCount = float("%0.2f"% (100 - (100*(bytes_remaining/self.MaxfileSize))))
Is called without passing a value for bytes_remaining which ends up in doing a division of None by self.MaxfileSize
See here for how to register a progress_bar callback with pytube:
How to add progress bar?

How to read a Kivy.properties.NumericProperty value in my code at a specific point

So basically I have a kivy project in which,I have a layout that I use in many classes,as such..I have made in custom and put it in a separate file so I can just reference it from different parts of my code.
Snippet:
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''
<CustLayout>:
#code here
''')
class CustLayout(BoxLayout):
t_length = NumericProperty(0)
my_len = 0
print(my_len)
def __init__(self, **kwargs):
super(Silvertable,self).__init__(**kwargs)
self.bind(t_length=self.on_t_length)
#This statement is executed after all other prints
print(self.t_length)
def on_t_length(self,instance,length):
#I'd like to get kv file value before the next line
self.my_len = length
print(my_len)
My kiv file:
#:import Silvertable silvertables.Silvertable
#chunk of code
BoxLayout:
Silvertable:
t_length: 5
Here,I DO get the value but unfortunately too late.That is,I get the value after the program has finished.my_len Doesn't change it's still 0
Bind Kivy Properties
The value of my_len is 0 (zero) because the print() functions were executed first before the run() method.
The value of my_len did change from 0 to 5 as per binding on property of t_length.
Please refer to the example and trace for details.
Example
main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder
Builder.load_string('''
<CustLayout>:
t_length: 5
''')
class CustLayout(BoxLayout):
t_length = NumericProperty(0)
my_len = 0
print("\tCustLayout.class level-start: my_len=", my_len)
def __init__(self, **kwargs):
super(CustLayout,self).__init__(**kwargs)
print("\nCustLayout.__init__:")
self.bind(t_length=self.on_t_length)
#This statement is executed after all other prints
print("\tself.t_length=", self.t_length)
print("\tself.my_len=", self.my_len)
def on_t_length(self, instance, length):
print("\nCustLayout.on_t_length:")
#I'd like to get kv file value before the next line
self.my_len = length
print("\tself.my_len=", self.my_len)
print("\tCustLayout.class level-end: my_len=", my_len)
class TestBindProperty(App):
def build(self):
print("\nTestBindProperty.build:")
return CustLayout()
def on_stop(self):
print("\tTestBindProperty.on_stop: my_len=", self.root.my_len)
if __name__ == "__main__":
TestBindProperty().run()
Output

Invalid syntax when trying to add patch_http_response_read patch

Hello i'm trying to patch my python code with http://bobrochel.blogspot.com/2010/11/bad-servers-chunked-encoding-and.html but when adding this snippet anywhere in the code I always get invalid syntax. What am I doing wrong?
The start of my code looks like this:
import logging
import argparse
import sys
from arbitrer import Arbitrer
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead, e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
class ArbitrerCLI:
def __init__(self):
except doesn't work that way anymore.
except httplib.IncompleteRead as e:
Indent correctly.
The try statement changed in Python 3.x.
import httplib
import logging
import argparse
import sys
from arbitrer import Arbitrer
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead as e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
class ArbitrerCLI:
def __init__(self):
...

Resources