0

So, according to this and this, to run two python scripts simultaneously I should run them from a batch file, separated by a &.

However, this does not seem to be working in a simple example.

I am currently trying this:

test1.py

import time
for i in range(5):
    time.sleep(1)
    print("Printing, test1:"+str(i))

test2.py

import time
for i in range(5):
    time.sleep(2)
    print("Printing, test2:"+str(i))

batch file

call "C:\Users\Username\Anaconda3\Scripts\activate.bat"
"C:\Users\Username\Anaconda3\python.exe" "C:\Users\Python\Documents\Python\Test\test1.py" &
"C:\Users\Username\Anaconda3\python.exe" "C:\Users\Python\Documents\Python\Test\test2.py" &

I would expect to see the results mingled, however, this is the outcome: outcome3

It is clear that script 2 is running after script 1.

Any ideas?

Thanks!

Andres Silva
  • 874
  • 1
  • 7
  • 26
  • Both of your linked questions are clearly talking about Unix shell scripts, *not* Windows batch files. – jasonharper Jul 27 '20 at 02:25
  • Wow.. I didn't pick up on that. Thanks! Any way to do it on Windows? – Andres Silva Jul 27 '20 at 02:27
  • `&` concatenate commands in batch file, so second is run after first has finished. to run both use `start “” “first command”` `start “” “second command"`. note first pair of quotes are window title. see `start /?` for further information – elzooilogico Jul 27 '20 at 10:14

2 Answers2

0

Use multiprocessing or threading modules of python

import time
import threading
def test1():
    for i in range(5):
        time.sleep(1)
         print("Printing, test1:"+str(i))
def test2():
    for i in range(5):
        time.sleep(2)
        print("Printing, test2:"+str(i))
x = threading.Thread(target=test1)
t = threading.Thread(target=test2)
x.start()
t.start()
Ujjwal Dash
  • 767
  • 1
  • 4
  • 8
  • Thanks. However, this didn't work for me. I am still getting one result after the other. I tried both, from a batch file and from PyCharm. – Andres Silva Jul 27 '20 at 02:31
0

Thanks to @jasonharper pointing out that the two solutions I had found were specific to Unix, not Windows (although I had searched for Windows), I was able to find this other post, that is for Windows.

With a little adaptation to conda, I was able to get bot scritps to run simultaniously, like this:

batch file

call "C:\Users\Username\Anaconda3\Scripts\activate.bat"
start python "C:\Users\Username\Documents\Python\Test\test1.py" &
start python "C:\Users\Username\Documents\Python\Test\test2.py" &

The results are pretty cool.. Two python windows running simultaneously: results2

Thanks everyone!

Andres Silva
  • 874
  • 1
  • 7
  • 26