Run multiple python scripts concurrently

2020-01-24 02:21发布

How can I run multiple python scripts? At the moment I run one like so python script1.py.

I've tried python script1.py script2.py and that doesn't work: only the first script is run. Also, I've tried using a single file like this;

import script1
import script2

python script1.py
python script2.py

However this doesn't work either.

9条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-24 03:02

I had to do this and used subprocess.

import subprocess

subprocess.run("python3 script1.py & python3 script2.py", shell=True)
查看更多
小情绪 Triste *
3楼-- · 2020-01-24 03:06

You can use Gnu-Parallel to run commands concurrently, works on Windows, Linux/Unix.

parallel ::: "python script1.py" "python script2.py"

查看更多
Deceive 欺骗
4楼-- · 2020-01-24 03:07

You try the following ways to run the multiple python scripts:

  import os
  print "Starting script1"
  os.system("python script1.py arg1 arg2 arg3")
  print "script1 ended"
  print "Starting script2"
  os.system("python script2.py arg1 arg2 arg3")
  print "script2 ended"

Note: The execution of multiple scripts depends purely underlined operating system, and it won't be concurrent, I was new comer in Python when I answered it.

Update: I found a package: https://pypi.org/project/schedule/ Above package can be used to run multiple scripts and function, please check this and maybe on weekend will provide some example too.

i.e: import schedule import time import script1, script2

 def job():
     print("I'm working...")

 schedule.every(10).minutes.do(job)
 schedule.every().hour.do(job)
 schedule.every().day.at("10:30").do(job)
 schedule.every(5).to(10).days.do(job)
 schedule.every().monday.do(job)
 schedule.every().wednesday.at("13:15").do(job)

 while True:
     schedule.run_pending()
     time.sleep(1)
查看更多
▲ chillily
5楼-- · 2020-01-24 03:08

If you want to run two Python scripts in parallel then just include the following at the end of your script:

if __name__=="__main__":
     Main()
查看更多
地球回转人心会变
6楼-- · 2020-01-24 03:10

I do this in node.js (on Windows 10) by opening 2 separate cmd instances and running each program in each instance.

This has the advantage that writing to the console is easily visible for each script.

I see that in python can do the same: 2 shells.

You can run multiple instances of IDLE/Python shell at the same time. So open IDLE and run the server code and then open up IDLE again, which will start a separate instance and then run your client code.

查看更多
迷人小祖宗
7楼-- · 2020-01-24 03:16

The most simple way in my opinion would be to use the PyCharm IDE and install the 'multirun' plugin. I tried alot of the solutions here but this one worked for me in the end!

查看更多
登录 后发表回答