LaVOZs

The World’s Largest Online Community for Developers

'; python 3.x - How to run two scripts at the same time - LavOzs.Com

How to run two scripts at the same time

In line x in script A, I want to start running script B, which takes 10 seconds. However, I do not want line x+1 to be executed 10 seconds after line x. Is there a way to fix this?

Script B is simply an independent series of command sent to another external device. Script A is used to monitor that device. Script B does not have any return, and code after line x in script A does not rely on script B.

Overall, I want to trigger the start of Script B and let it run independent of Script A. While script A is kept running continuously.


Thanks to the comment, I found subprocess.Popen() can do the work.

Actually, Script B can be simplified into one single function (Function B). In this case, shall I create one Python script as Script B that only calls Function B, and use subprocess.Popen() to call Script B in Script A?

Or, is there a better way to call Function B, rather than Script B, in a similar fashion as in subprocess.Popen()?

I am trying to call Function B directly because my task is very time-dependent, and half a second of delay may be significant. I have measured the delay from the line x-1 in Script A to line 1 in Script B, if I call Script B in Script A. The delay is ~450 ms. I suspect the delay is from the time for the interpreter to compile Script B and execute it, even though Script B is one or two lines long.


Thank you very much!

How to run two scripts at the same time:

Use the GNU parallel ( sudo apt install parallel if not already installed on your system )

Alan@Enigma:~$ parallel python ::: TheScript_A TheScript_B [ TheScript_C [ ... ]]

This way is way cheaper, than trying to orchestrate process-spawns from inside the first python session. It is possible, yet the processing costs and latency side-effects and software engineering costs are way higher, than using the smart O/S services present right for this simple problem-definition.

Reading man parallel you get all the smart bash-scripting options to add for flexible, parametrised process-options, as one may need and wish

...
total_jobs()         number of jobs in total
slot()               slot number of job
seq()                sequence number of job
...
Related
How can I represent an 'Enum' in Python?
How to flush output of print function?
How do I update the GUI from another thread?
Using subprocess to run Python script on Windows
How to use threading in Python?
Running shell command and capturing the output
C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?
Python subprocess executed script wont write to file
python import module vs running script as subprocess.popen
Running non-blocking python script from another script with multiple parameters and logging