Python timer with threading - python

I wanted to create a simple timer script to use it with my telegram bot, but something doesn't work like I want it to. Here is the code:
#!/usr/bin/python
from threading import Timer
class Timer:
def __init__(self, router):
self.routes = [
("^/timer\s(?P<time>[^$]+)$", self.main),
]
def timer_end(self):
print 'Timer End'
def main(self, message, match):
Timer(5, self.timer_end, ()).start()
I always get this error:
TypeError: __init__() takes exactly 2 arguments (4 given)
It would be great if someone could help.
Thanks in advance!

As #swstephe mentioned in a comment:
You import Timer, then you create a class which overwrites Timer. Maybe you should just "import threading" then use "threading.Timer" to distinguish the two?

Related

Variable not found in asynchronous classes

I have a little problem, in fact, I am trying to make the game of life but without searching on google and I would like to make two classes, the first one that proceed the tkinter app and the second one that proceed the game it self (moving cells...).
The fact is, when I try to implement a pause button, it doesn't works because of the while of the game class or its recursive function... Well, the process of the app is completly used by the loop.
I then tried to make it with asynchronous methods and to well understand them I tried with an own example :
`
import asyncio
from async_class import AsyncClass
class Foo():
async def __ainit__(self):
self.test = 'Hi'
return
#
def show(self):
print(self.test)
#
class Bar():
async def __ainit__(self):
return
#
#
async def main():
foo = Foo()
asyncio.create_task(foo.show())
bar = Bar()
if __name__ == '__main__':
asyncio.run(main())
`
Here I then have an error that says : AttributeError: 'Foo' object has no attribute 'test'...
To you have any idea to fix that ? or even a ethod to permit a pause into the game ?
I hope you'll have a solution,
Thx

Missing argument self when scheduling method

I'd like to schedule a method using the schedule module but it doesn't work.
The error message is as follows:
Warning: Missing Argument 'self'.
Here is my code:
def p_b(self):
do
print('hello')
do
do
schedule.every().minute.do(p_b)
while True:
schedule.run_pending() # error comes out.
time.sleep(1)
As the error indicates, you added "self" to the method. Self represent an instance of a class that is passed automatically when you make a call, see here fore more info.
So try to remove the self parameter and it should just work:
import schedule
import time
def p_b():
print('hello')
schedule.every().minute.do(p_b)
while True:
schedule.run_pending()
time.sleep(1)
Edit
If you do have that method inside a class and you have the scheduler outside, you need to call it from an instance of the class e.g.:
import schedule
import time
class SomeClass:
def p_b(self):
print('hello')
if __name__=='__main__':
some_class = SomeClass()
schedule.every().minute.do(some_class.p_b)
while True:
schedule.run_pending()
time.sleep(1)

Passing connection from method to other method in Python using subprocess and rpyc

Trying to create a library, which does this-Connect to Unix box, pass this connection to next method and run a shell script. Also i am calling this methods in other file.
New to python, please help.
file1:
from file2 import *
def start():
one=libs()
one.connect()
one.run()
file2:
import rpyc
class libs():
def connect(self):
self.conn=rpyc.classic.connect("hostname")
self.remote=self.conn.modules.subprocess
return
def run(self):
p1="sh -vx /tmp/test.sh"
self.result=self.remote.Popen(p1,shell=True,stdout=remote.PIPE,stderr=remote.PIPE)
out,err=self.result.communicate()
print out,err
return out,err
What wrong am i doing, I m trying to implement OOPS here.Getting no error or output just code exits with 0
have tried this also combining both methods in file2 into one,and then calling one method only in file1.
import rpyc
class libs():
p1="sh -vx /tmp/test.sh"
def connect(self,p1):
self.conn=rpyc.classic.connect("hostname")
self.remote=self.conn.modules.subprocess
self.result=self.remote.Popen(p1,shell=True,stdout=remote.PIPE,stderr=remote.PIPE)
out,err=self.result.communicate()
print out,err
return out,err
Have you tried to start learning python first ?
When you call a function or a method or whatever is callable you need parenthesis...
def start():
one=libs()
one.connect()
one.run()

About Python global variable

import sys
from threading import Thread
is_online=1
class CommandListenerThread(Thread):
global is_online
def run(self):
while is_online:
next_command=sys.stdin.readlines();
if next_command == 'exit':
is_online=0
else:
print next_command
listener=CommandListenerThread()
listener.start()
When I run this python code,it shows an error: "UnboundLocalError: local variable 'is_online' referenced before assignment"
I tested another code which uses the same way to access the global variable inside a class,and it works fine. So,what is wrong with this specific code?
the code may look weird which using a thread to listen the command line,but it is just
a part of my program which gets an error when I run the whole program.
thank you guys
Move global is_online into run() to solve the error.
To address your other question (in a comment below), why not make it a static class variable ?
class CommandListenerThread(Thread):
is_online = 1
def run(self):
print CommandListenerThread.is_online
In case that you have to use another code with a global is_online, you can take the DI (dependency injection) approach as follows:
import sys
from threading import Thread
is_online = 2
class CommandListenerThread(Thread):
def __init__(self, is_online):
super(CommandListenerThread, self).__init__()
CommandListenerThread.is_online = is_online # now it's a static member
# if you want to make it an instance member use self.is_online
def run(self):
print CommandListenerThread.is_online
listener=CommandListenerThread(is_online) # inject the value to the constructor
listener.start()

Multithreading python (using _thread), doesn't do anything

First of all, here are my two python files:
sred.py:
import _thread,time
class Thread:
def __init__(self,time:int,say:str):
self.time=time
self.say=say
def create():
id = _thread.get_ident()
for i in range(5):
print("HALLO", id)
return
from sred import Thread
import time,_thread
_thread.start_new_thread(Thread.create,())
The second one:
main.py
from sred import Thread
import time,_thread
_thread.start_new_thread(Thread.create,())
when executing this it doesn't print anything out, why?
UPDATE:
import _thread
class Thread:
#classmethod
def create():
id = _thread.get_ident()
for i in range(5):
print("HALLO", id)
return
main.py:
from sred import Thread
import time,_thread
_thread.start_new_thread(Thread().create,())
Is this now right, or is there still something wrong?
The create method is missing self as a parameter -- it looks like it should also be a #classmethod if you want to call it as it's written now. Note that your __init__ method is never getting called, because you never instantiate any Thread objects. You may want it to read:
_thread.start_new_thread(Thread().create, ())
i.e., instantiate a thread, then pass its create method to be executed in the new thread. I'm not sure what's happening, but I suspect that something is erroring and the stacktrace is being suppressed by something.
Also, you need to delete the space after the for statement -- it's significant, and it should be throwing you a syntax error about an unexpected indent.
EDIT:
This version runs on my machine:
import _thread
class Thread:
def create(self):
id = _thread.get_ident()
for i in range(5):
print("HALLO", id)
return
_thread.start_new_thread(Thread().create, ())

Categories