why am i getting a index is out of range error - python

from tkinter import *
import pytube
import threading
def download():
link = test_url.get()
yt = pytube.YouTube(link)
videos = yt.get_videos()
n = quality.get()
vid = videos[n - 1]
destination = destination_test.get()
vid.download(destination)
def test():
threading.Thread(target=download()).start()
root = Tk()
test_url = StringVar()
quality = IntVar()
destination_test = StringVar()
url_label = Label(text='Enter Url')
quality_label = Label(text='quality')
url_label.grid(row=0, column=0)
quality_label.grid(row=1, column=0)
destination_label = Label(text='Destination')
destination_label.grid(row=2, column=0)
url_entry = Entry(textvariable=test_url)
url_entry.grid(row=0, column=1)
quality_entry = Entry(textvariable=quality)
quality_entry.grid(row=1, column=1)
destination_entry = Entry(textvariable=destination_test)
destination_entry.grid(row=2, column=1)
download_button = Button(text='download', command=test())
download_button.grid(row=3, column=1)
root.mainloop()
Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition
2017.1.4\helpers\pycharm_jb_unittest_runner.py", line 35, in
main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not
JB_DISABLE_BUFFERING) File "C:\Python36\lib\unittest\main.py", line
93, in init
self.parseArgs(argv) File "C:\Python36\lib\unittest\main.py", line 140, in parseArgs
self.createTests() File "C:\Python36\lib\unittest\main.py", line 147, in createTests
self.module) File "C:\Python36\lib\unittest\loader.py", line 219, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names] File "C:\Python36\lib\unittest\loader.py", line 219, in
suites = [self.loadTestsFromName(name, module) for name in names] File "C:\Python36\lib\unittest\loader.py", line 153, in
loadTestsFromName
module = import(module_name) File "C:\Users\Matthew\PycharmProjects\test\test.py", line 37, in
download_button = Button(text='download', command=test()) File "C:\Users\Matthew\PycharmProjects\test\test.py", line 19, in test
threading.Thread(target=download()).start() File "C:\Users\Matthew\PycharmProjects\test\test.py", line 13, in download
vid = videos[n - 1] IndexError: list index out of range

Because the value of your variable 'n' either equals to 0, or it's larger than your number of videos by 2 or more.
Whatever quality.get() does, whatever quality variable is, n=quality.get() is the line that eventually causes error...

Related

line 17, in __init__ self.win = tk.Tk() TypeError: __init__() takes 2 positional arguments but 3 were given

I'm trying to create a desktop interface using tkinter. I have used all the tips on the websites for this problem. It didn't help in any way.
The error is given up by the line: win = tk.Tk(). What should I do to make the code work? Full code: https://drive.google.com/drive/folders/1NoUBRFDc76WA1rkUSV5_602drRj9P3f6?usp=sharing
win = tk.Tk()
win.title('wave simualator')
win.geometry('1024x650')
# win.resizable(False, False)
tabControl = ttk.Notebook(win)
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
win.mainloop()
Full error traceback:
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\13\main.py", line 213, in <module>
win = tk.Tk()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2272, in __init__
self._loadtk()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2306, in _loadtk
self.protocol("WM_DELETE_WINDOW", self.destroy)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2194, in wm_protocol
command = self._register(func)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1517, in _register
f = CallWrapper(subst, func,).__call__
TypeError: __init__() takes 2 positional arguments but 3 were given

Converting video into audio error appiers while using moviepy in python

I wanted to make a code that converts video into audio by a button in python
and that is my code:
from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfile
from moviepy.editor import *
def def_button():
global Mp4
global Mp4_Data
Mp4 = askopenfile()
if str(Mp4.name)[-4:] != ".mp4":
Mp4_Data = Label(root, text="That's NOT a Mp4 Video", font="decorative 9 bold", fg="red").grid(row=9, column=0,
columnspan=3)
else:
inactive_buttons() #function to make the button inactive to avoid double clicks
mp4_frames = AudioFileClip(Mp4.name)
audio = str(Mp4.name).replace(".mp4", ".mp3")
mp4_frames.write_audiofile(audio)
Mp4_Data = Label(root, text="The Audio Is being Uploaded into Video's Path", font="decorative 9 bold", fg="red") #feed back for the user
Mp4_Data.grid(row=9, column=0, columnspan=3)
assert isinstance(mp4_frames, object)
mp4_frames.close()
active_buttons() #function to make the button active after downloading
button = Button(root, text="Convert a Video into Audio", font="decorative 9 bold", width=50, fg="white", bg="#EF0000",
command=def_button)
button.grid(row=10, column=0, columnspan=3)
Mp4_Data = Label(root, text=" ").grid(row=9, column=0, columnspan=3)
but somehow there is a big error output:
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\io\readers.py", line 193, in get_frame
result[in_time] = self.buffer[indices]
IndexError: index -100001 is out of bounds for axis 0 with size 0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\YT_Video_Downloader.py", line 115, in def_button6
mp4_frames.write_audiofile(Mp4.name+".mp3")
File "<decorator-gen-45>", line 2, in write_audiofile
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\decorators.py", line 54, in requires_duration
return f(clip, *a, **k)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\AudioClip.py", line 206, in write_audiofile
return ffmpeg_audiowrite(self, filename, fps, nbytes, buffersize,
File "<decorator-gen-9>", line 2, in ffmpeg_audiowrite
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\decorators.py", line 54, in requires_duration
return f(clip, *a, **k)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\io\ffmpeg_audiowriter.py", line 166, in ffmpeg_audiowrite
for chunk in clip.iter_chunks(chunksize=buffersize,
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\AudioClip.py", line 85, in iter_chunks
yield self.to_soundarray(tt, nbytes=nbytes, quantize=quantize,
File "<decorator-gen-44>", line 2, in to_soundarray
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\decorators.py", line 54, in requires_duration
return f(clip, *a, **k)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\AudioClip.py", line 127, in to_soundarray
snd_array = self.get_frame(tt)
File "<decorator-gen-11>", line 2, in get_frame
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\decorators.py", line 89, in wrapper
return f(*new_a, **new_kw)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\Clip.py", line 93, in get_frame
return self.make_frame(t)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\io\AudioFileClip.py", line 77, in <lambda>
self.make_frame = lambda t: self.reader.get_frame(t)
File "C:\Users\Stem Asyut\PycharmProjects\pythonProject\venv\lib\site-packages\moviepy\audio\io\readers.py", line 205, in get_frame
result[in_time] = self.buffer[indices]
IndexError: index -100001 is out of bounds for axis 0 with size 0
and I don't know why that's happening.
I tried a lot of things and I have the same problem.
SO is there anyone who could help me with that problem because I didn't find anything about that on the internet?

Invalid command name ".!editspeakers.!canvas.!frame.!entry"

When my program is compiled via pyinstaller I run into this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1892, in __call__
File "editSpeakers.py", line 67, in <lambda>
File "editSpeakers.py", line 52, in autoUpdateSpeakers
File "tkinter\__init__.py", line 3043, in get
_tkinter.TclError: invalid command name ".!editspeakers.!canvas.!frame.!entry"
I presume this is a tkinter problem but I have no idea how to fix it and it only shows up when ran via pyinstaller not when ran via the IDE
Code Snippets:
def populate(self):
speakers = main.openSpeakers()
speakersList = sorted(speakers.items())
numRows = len(speakers) + 3
for i in range(numRows):
self.key = tk.Entry(self.frame, width=20, fg="blue", font=("Arial", 16, "bold"))
self.value = tk.Entry(self.frame, width=20, fg="blue", font=("Arial", 16, "bold"))
self.key.grid(row=i, column=0)
self.value.grid(row=i, column=1)
EditSpeakers.entryList.append([self.key, self.value])
try:
self.key.insert(0, speakersList[i][0])
self.value.insert(0, speakersList[i][1])
except IndexError: pass
def autoUpdateSpeakers(self, root):
speakers = dict()
try:
for key, value in EditSpeakers.entryList:
if key.get():
speakers[key.get()] = value.get()
with open("speakers.json", "w") as f:
json.dump(speakers, f, indent=4)
except Exception as e: print(e) ## << Error happening here
finally: root.destroy()
You can find my full code here

Tkinter with multiprocessing: OSError [Errno 22] Invalid argument

I'm trying to add multiprocessing to my tkinter app and I've been having issues with the error: TypeError: cannot pickle '_tkinter.tkapp' object. I had a look at the solution proposed in the question here and tried to implement my own version of it and this appears to have solved this particular error but now I instead I have constant OSError: [Errno 22] Invalid argument:
What I aspire to have the code do is that some calculation is being performed in the background and results of this calculation are being put into the Queue (here just integers but will be Numpy arrays in the actual code). The GUI application then displays some statistics and results to the user.
from multiprocessing import Process, Queue
from queue import Empty
import tkinter as tk
from tkinter import Tk
class FooUI(Process):
def __init__(self, q: Queue):
super().__init__(target=self, args=(q,))
self.queue = q
self.duh = []
self.root = Tk()
self._create_interface()
self.root.after(100, self._check_queue)
self.root.mainloop()
def _check_queue(self):
try:
out = self.queue.get_nowait()
if out:
self.duh.append(out)
print(self.duh)
return
except Empty:
pass
self.root.after(100, self._check_queue)
def _create_interface(self):
self.root.geometry("100x100")
b = tk.Button(self.root, text='Start', command=self.calc)
b.grid(row=0, column=0)
def calc(self):
p = Process(target=do_calc)
p.start()
def do_calc(q: Queue):
for i in range(20):
q.put(i**2)
If __name__ == '__main__':
q = Queue()
f = FooUI(q)
f.start()
And here is the traceback:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 125, in _main
prepare(preparation_data)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 236, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
main_content = runpy.run_path(main_path,
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 264, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 234, in _get_code_from_file
with io.open_code(decoded_path) as f:
OSError: [Errno 22] Invalid argument: 'C:\\python\\block_model_variable_imputer\\<input>'
Traceback (most recent call last):
File "<input>", line 3, in <module>
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_tkinter.tkapp' object
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 125, in _main
prepare(preparation_data)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 236, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
main_content = runpy.run_path(main_path,
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 264, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\cherp2\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 234, in _get_code_from_file
with io.open_code(decoded_path) as f:
OSError: [Errno 22] Invalid argument: 'C:\\python\\block_model_variable_imputer\\<input>'
I've been trying for a while to get it to work. Any help will be greatly appreciated!
You do the subclass of Process() in a wrong way. You need to override the run() method instead of passing target option.
from multiprocessing import Process, Queue
from queue import Empty
import tkinter as tk
class FooUI(Process):
def __init__(self, q: Queue):
super().__init__() # don't pass target and args options
self.queue = q
self.duh = []
# override run() method and create the Tk() inside the function
def run(self):
self.root = tk.Tk()
self._create_interface()
self.root.after(100, self._check_queue)
self.root.mainloop()
def _check_queue(self):
try:
out = self.queue.get_nowait()
if out:
self.duh.append(out)
print(self.duh)
#return
except Empty:
pass
self.root.after(100, self._check_queue)
def _create_interface(self):
self.root.geometry("100x100")
b = tk.Button(self.root, text='Start', command=self.calc)
b.grid(row=0, column=0)
def calc(self):
if self.queue.empty():
self.duh.clear()
p = Process(target=do_calc, args=[self.queue]) # pass self.queue to do_calc()
p.start()
def do_calc(q: Queue):
for i in range(20):
q.put(i**2)
if __name__ == '__main__':
q = Queue()
f = FooUI(q)
f.start()

Backtrader giving IndexError: array assignment index out of range

I am trying to run the following strategy:
def max_n(array, n):
return np.argpartition(array, -n)[-n:]
class CrossSectionalMR(bt.Strategy):
params = (
('num_positions', 100),
)
def __init__(self, temp):
self.inds = {}
for d in self.datas:
self.inds[d] = {}
self.inds[d]["pct"] = bt.indicators.PercentChange(d.close, period=1)
def prenext(self):
self.next()
def next(self):
available = list(filter(lambda d: len(d), self.datas)) # only look at data that existed yesterday
rets = np.zeros(len(available))
for i, d in enumerate(available):
rets[i] = self.inds[d]['pct'][0]
market_ret = np.mean(rets)
weights = -(rets - market_ret)
max_weights_index = max_n(np.abs(weights), self.params.num_positions)
max_weights = weights[max_weights_index]
weights = weights / np.sum(np.abs(max_weights))
for i, d in enumerate(available):
if i in max_weights_index:
self.order_target_percent(d, target=weights[i])
else:
self.order_target_percent(d, 0)
The full error is:
Traceback (most recent call last):
File "/home/poblivsig/Software/pycharm-2020.3.1/plugins/python/helpers/pydev/pydevd.py", line 1477, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/poblivsig/Software/pycharm-2020.3.1/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/poblivsig/Dropbox/meanrev/main.py", line 190, in <module>
dd, cagr, sharpe = backtest(datas, CrossSectionalMR, plot=True, num_positions=100)
File "/home/poblivsig/Dropbox/meanrev/main.py", line 181, in backtest
results = cerebro.run()
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/cerebro.py", line 1293, in runstrategies
self._runonce(runstrats)
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/cerebro.py", line 1652, in _runonce
strat._once()
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/lineiterator.py", line 297, in _once
indicator._once()
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/lineiterator.py", line 297, in _once
indicator._once()
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/linebuffer.py", line 630, in _once
self.oncestart(self._minperiod - 1, self._minperiod)
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/lineroot.py", line 165, in oncestart
self.once(start, end)
File "/home/poblivsig/Dropbox/meanrev/venv/lib/python3.8/site-packages/backtrader/linebuffer.py", line 672, in once
dst[i] = src[i + ago]
IndexError: array assignment index out of range
python-BaseExceptio
Any help would be greatly appreciated.
I grab the data from Yahoo and store it in csv files which are then loaded up and added to Cerebro. Sometimes, the code cannot get the full list of the SPY, but I don't think that is the problem here.

Categories