简体   繁体   中英

Running multiple Python Scripts from one file

I have 3 scripts that needs to be executed. Two of them have continuous loop and will never stop runing as long as sensors are sending the data, and 3rd script will run only once every hour.

So lets say i have them like this:

sensorscript1 sensorscript2 Export

What would be the best method to create one single file to run this process? Would using threading be the best way to go in this case?

import sensorscript1, sensorscript2
from threading import Thread

Or would Flask app be better suited for this? Any other suggestions?

There is another approach to do this if you want each script to run in a new window & maybe look at the logs on it.

You could run one script that calls the other scripts using a subprocess call.

import subprocess

subprocess.call("start cmd /K python sensorscript1.py", shell=True) 
                         # this opens the script1.py file in a new console window (shell=True)
subprocess.call("start cmd /K python sensorscript2.py", shell=True)
subprocess.call("start cmd /K python Export.py", shell=True)

Or alternatively you can run Export & call the other two scripts from it - it's upto you to decide how it runs best for you.

Use PyThreads, a new threading library for python. https://github.com/Narasimha1997/PyThreads , this makes running threads much more easier.

For example you have 3 script files, f1, f2 and f3, write functions in all these 3 files as threads using PyThreads

Example : File -1

from pythreads import pythread
@pythread
def fun1() : 
  #some logic
  pass

File -2:

from pythreads import pythread

@pythread
def fun2():
   #some logic
   pass

Now in main file import them

from file1 import fun1
from file2 import fun2

#call these functions, because of @pythreads, they start behaving like threads
fun1()
fun2()

#your function 3
def fun3():
  #some logic 
  pass

#call it here
if __name__ == "__main__" :
   fun3()

PS: I wrote PyThreads to make thread usage easier in python

You pretty much got it

import sensorscript1, sensorscript2
from threading import Thread

t1 = Thread(target=sensorscript1, args=(arg1, arg2))
t2 = Thread(target=sensorscript2, args=(arg,))

t1.run()
t2.run()

Note the args parameter is only needed if you are passing arguments to the function. Also note the extra comma. This is because the args parameter requires a Tuple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM