天天看點

python 循環觸發一次,python同時執行多個循環

python 循環觸發一次,python同時執行多個循環

I know that it is not possible to run multiple loops at the same time in Python.

Anyhow, what I need to achieve is that I have one loop running reading loads of sensor data, every 0.25 seconds.

At the same time I have signal devices running in parallel that need to send signals every 3 seconds.

My question is what way is best practice to achieve this?

Does it make sense to write two scripts and run them in parallel?

Does it make sense to use threading?

Is there any other possibility in order to make this work?

I would be greatful for code samples.

Thank you!

Edit:

Both loops are absolutely independent.

So, let's say while script 1 is running, reading the sensor data, when one of the sensors received a value < 300, it should run script 2 which will send the signals. At the same time when the sensors data gets > 300 it should stop script 2.

解決方案

"Python multiple loops at the same time. I know that it is not possible [...]" - this looks really funny.

It is possible to run two loops at the same time, exactly how you described it. And both ways make much sense, depending on what do you actually need and want. If the tasks are completely independent you should run it as two scripts. If you need those two loops to realize one task and it makes sense for them to be in one file you can use multiprocessing.

Tested for python 2.7.5+ and 3.3.2+.

Here is some minimal example:

from multiprocessing import Process

import time

def f(name):

print('hello', name)

time.sleep(10)

def d(name):

print('test2', name)

time.sleep(10)

if __name__ == '__main__':

p1 = Process(target=f, args=('bob',))

p2 = Process(target=d, args=('alice',))

p1.start()

p2.start()

p1.join()

p2.join()

Script runs for 10s and both strings are printed right away, which means everything works.

time python3 ./process.py

hello bob

test2 alice

real 0m10.073s

user 0m0.040s

sys 0m0.016s