Python - How can I run two dependant funtions at the same time?
Python - How can I run two dependant funtions at the same time?
I have two funtions, one runs increasing by one a number, and the other needs to capture the number that is running the first function every 5 seconds, so that when I capture the first number is 0, the sencond one is 10, the next one is 15, and so on... this is simulating the first function as a sensor. My code is as follows:
import time
import threading
from threading import Thread
def numero(i=0):
while True:
i = i + 1
time.sleep(1)
#print i
def capturar():
while True:
posicion = numero()
time.sleep(5)
print posicion
if __name__ == '__main__':
Thread(target = capturar()).start()
Thread(target = numero()).start()
When I run this code, it keeps in the first function, how can I get this run correctly and obtain the capture of the series of numbers every 5 seconds?
numero
None
numero()
Calling this:
posicion = numero()
will again start the first counter loop inside your second thread.– Matt Clark
Jul 2 at 3:35
posicion = numero()
if you can upgrade to
3.5
+, asyncio
would help substantially with async
and await
– Matthew Story
Jul 2 at 3:47
3.5
asyncio
async
await
@MatthewStory But the OP wants to do this with threading in Python 2. And that's reasonable, although they really ought to migrate to Python 3.
– PM 2Ring
Jul 2 at 3:55
@PM2Ring I'm not sure doing anything with Threads in python is reasonable :troll: ;).
– Matthew Story
Jul 2 at 3:57
2 Answers
2
There are several mistakes in your code:
i
capturar
capturar
numero
Thread
numero
capturar
capturar
To help with the first one, the easiest solution is to wrap the functions into a class, and make i
into an instance state (as an attribute). The second one merely requires you to remove the extra parentheses. The third one is resolved with the first one, as there is no function call required any more to fetch the counter state.
i
This should do what you want:
import time
from threading import Thread
class Contador:
def __init__(self, comienzo = 0):
self.numero = comienzo
def producir(self):
while True:
self.numero += 1
time.sleep(1)
def capturar(self):
while True:
posicion = self.numero
time.sleep(5)
print posicion
if __name__ == '__main__':
c = Contador()
Thread(target = c.capturar).start()
Thread(target = c.producir).start()
Nice code, but why do you set the value of
posicion
but then sleep for 5 seconds before printing it? Wouldn't it be better to print the latest value?– PM 2Ring
Jul 2 at 4:01
posicion
@PM2Ring Don't ask me, ask OP. If that's an error, it's a business logic error, not a Python error.
– Amadan
Jul 2 at 4:02
Ok, I can't disagree with that. ;)
– PM 2Ring
Jul 2 at 4:08
Thank you Amadan, the soution that you share is working perfectlym but when I tried to pull it into the real sensor (GPS), I am getting only "0"
import gps
import itertools
import json
import os
import portdetect
import time
import serial
from threading import Thread
(puerto1, puerto2) = portdetect.detectar_puerto()
print puerto1, puerto2
port = serial.Serial(puerto1, 115200, timeout=1)
os.system('sudo systemctl stop gpsd.socket')
time.sleep(2)
os.system('sudo systemctl disable gpsd.socket')
time.sleep(2)
comando = 'sudo gpsd ' + puerto2 + ' -F /var/run/gpsd.sock'
os.system(str(comando))
#print str(comando)
# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
class Contador:
def __init__(self, comienzo = 0):
self.raw_datos = comienzo
def leergps(self):
while True:
try:
report = session.next()
# Wait for a 'TPV' report and display the current time
# To see all report data, uncomment the line below
# print report
if report['class'] == 'TPV':
if hasattr(report, 'time') or hasattr(report, 'lat') or hasattr(report, 'lon') or hasattr(report,
'speed'):
datos = [report.time, report.lat, report.lon, report.speed]
clave = ['tiempo', 'lat', 'lon', 'speed']
diccionario = dict(itertools.izip(clave, datos))
self.raw_datos = (json.dumps(diccionario))
# print raw_datos
return self.raw_datos
else:
return report['class']
except:
print "Error de coordenadas"
def capturar(self):
while True:
posicion = self.raw_datos
time.sleep(5)
print posicion
if __name__ == '__main__':
c = Contador()
Thread(target = c.capturar).start()
Thread(target = c.leergps()).start()
I am trying only to pull the "raw data obtained every 5 seconds, but I am not achieving this"
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
First thing first,
numero
never returns or yields anything, so you'll always getNone
fromnumero()
– RafaelC
Jul 2 at 3:35