Как запустить несколько скриптов python одновременно windows

I've to launch and execute 24 independent python scripts on windows 7. I want that one script launches them all at the same time... without ruling them all (I'm not Sauron) or waiting their ends. I...

You may use an indipendent process (multiprocessing.Process) and using two queues to communicate with it (multiprocessing.Queue) one for the input and the other one for the output.
Example on starting the process:

import multiprocessing

def processWorker(input, result):
    work = input.get()
    ## execute your command here
    pipe = subprocess.Popen(command, stdout = subprocess.PIPE,
                             stderr = subprocess.PIPE, shell = True)
    stdout, stderr = pipe.communicate()
    result.put(pipe.returncode)

input  = multiprocessing.Queue()
result = multiprocessing.Queue()

p = multiprocessing.Process(target = processWorker, args = (input, result))
p.start()
commandlist = ['ls -l /', 'ls -l /tmp/']
for command in commandlist:
    input.put(command)
for i in xrange(len(commandlist)):
    res = result.get(block = True)
    if not res is 0:
        print 'One command failed'

Then you may keep track of which command is being executed by each subprocess simply storing the command associated to a workid (the workid can be a counter incremented when the queue get filled with new work).
Usage of multiprocessing.Queue is robust since you do not need to rely on stdout/err parsing and you also avoid related limitation.
Moreover you can easily manage more subprocesses.

Then, you can also set a timeout on how long you want a get call to wait at max, eg:

import Queue
try:
    res = result.get(block = True, timeout = 10)
except Queue.Empty:
    print error

You may use an indipendent process (multiprocessing.Process) and using two queues to communicate with it (multiprocessing.Queue) one for the input and the other one for the output.
Example on starting the process:

import multiprocessing

def processWorker(input, result):
    work = input.get()
    ## execute your command here
    pipe = subprocess.Popen(command, stdout = subprocess.PIPE,
                             stderr = subprocess.PIPE, shell = True)
    stdout, stderr = pipe.communicate()
    result.put(pipe.returncode)

input  = multiprocessing.Queue()
result = multiprocessing.Queue()

p = multiprocessing.Process(target = processWorker, args = (input, result))
p.start()
commandlist = ['ls -l /', 'ls -l /tmp/']
for command in commandlist:
    input.put(command)
for i in xrange(len(commandlist)):
    res = result.get(block = True)
    if not res is 0:
        print 'One command failed'

Then you may keep track of which command is being executed by each subprocess simply storing the command associated to a workid (the workid can be a counter incremented when the queue get filled with new work).
Usage of multiprocessing.Queue is robust since you do not need to rely on stdout/err parsing and you also avoid related limitation.
Moreover you can easily manage more subprocesses.

Then, you can also set a timeout on how long you want a get call to wait at max, eg:

import Queue
try:
    res = result.get(block = True, timeout = 10)
except Queue.Empty:
    print error

I have python script run.py:

def do(i):
    # doing something with i, that takes time

start_i = sys.argv[1]
end_i = sys.argv[2]
for i in range(start_i, end_i):
    do(i)

Then I run this script:

python run.py 0 1000000

After 30 minutes script is completed.
But, it’s too long for me.

So, I create bash script run.sh:

python run.py 0 200000 &
python run.py 200000 400000 &
python run.py 400000 600000 &
python run.py 600000 800000 &
python run.py 800000 1000000

Then I run this script:

bash run.sh

After 6 minutes script is completed.
Rather good. I’m happy.

But I think, there is another way to solve the problem (without creating bash script), isn’t there?

asked Aug 26, 2012 at 0:04

imkost's user avatar

You’re looking for the multiprocessing package, and especially the Pool class:

from multiprocessing import Pool
p = Pool(5)  # like in your example, running five separate processes
p.map(do, range(start_i, end_i))

Besides consolidating this into a single command, this has other advantages over your approach of calling python run.py 0 200000 & etc. If some processes take longer than others (and therefore, python run.py 0 200000 might finish before the others), this will make sure all 5 threads keep working until all of them are done.

Note that depending on your computer’s architecture, running too many processes at the same time might slow them all down (for starters, it depends on how many cores your processor has, as well as what else you are running at the same time).

answered Aug 26, 2012 at 0:20

David Robinson's user avatar

David RobinsonDavid Robinson

76.2k16 gold badges163 silver badges183 bronze badges

1

You could have your python program create the independent processes, instead of bash doing it, but that’s not much different. What is it about your solution that you find deficient?

answered Aug 26, 2012 at 0:08

Scott Hunter's user avatar

Scott HunterScott Hunter

48.2k12 gold badges57 silver badges99 bronze badges

3

I have python script run.py:

def do(i):
    # doing something with i, that takes time

start_i = sys.argv[1]
end_i = sys.argv[2]
for i in range(start_i, end_i):
    do(i)

Then I run this script:

python run.py 0 1000000

After 30 minutes script is completed.
But, it’s too long for me.

So, I create bash script run.sh:

python run.py 0 200000 &
python run.py 200000 400000 &
python run.py 400000 600000 &
python run.py 600000 800000 &
python run.py 800000 1000000

Then I run this script:

bash run.sh

After 6 minutes script is completed.
Rather good. I’m happy.

But I think, there is another way to solve the problem (without creating bash script), isn’t there?

asked Aug 26, 2012 at 0:04

imkost's user avatar

You’re looking for the multiprocessing package, and especially the Pool class:

from multiprocessing import Pool
p = Pool(5)  # like in your example, running five separate processes
p.map(do, range(start_i, end_i))

Besides consolidating this into a single command, this has other advantages over your approach of calling python run.py 0 200000 & etc. If some processes take longer than others (and therefore, python run.py 0 200000 might finish before the others), this will make sure all 5 threads keep working until all of them are done.

Note that depending on your computer’s architecture, running too many processes at the same time might slow them all down (for starters, it depends on how many cores your processor has, as well as what else you are running at the same time).

answered Aug 26, 2012 at 0:20

David Robinson's user avatar

David RobinsonDavid Robinson

76.2k16 gold badges163 silver badges183 bronze badges

1

You could have your python program create the independent processes, instead of bash doing it, but that’s not much different. What is it about your solution that you find deficient?

answered Aug 26, 2012 at 0:08

Scott Hunter's user avatar

Scott HunterScott Hunter

48.2k12 gold badges57 silver badges99 bronze badges

3

Как я могу запустить несколько скриптов Python? В данный момент я запускаю такой как python script1.py.

Я пробовал python script1.py script2.py, и это не работает: запускается только первый скрипт. Кроме того, я попытался использовать один файл, как это;

import script1
import script2

python script1.py
python script2.py

Однако это тоже не работает.

8 ответов

Лучший ответ

С Bash:

python script1.py &
python script2.py &

Вот и весь сценарий. Он будет запускать два скрипта Python одновременно.

Python мог бы сделать то же самое сам, но это заняло бы намного больше времени, и это плохой выбор для рассматриваемой проблемы.

Я думаю, что возможно, что вы используете неправильный подход к решению вашей проблемы, и я хотел бы услышать, к чему вы клоните.


54

Christopher Peterson
16 Фев 2015 в 20:28

Я должен был сделать это и использовал подпроцесс.

import subprocess

subprocess.run("python3 script1.py & python3 script2.py", shell=True)


2

user2757128
8 Июн 2019 в 14:26

Если вы хотите запустить два скрипта Python параллельно, просто включите следующее в конец скрипта:

if __name__=="__main__":
     Main()


-3

Inder
16 Мар 2019 в 16:52

На мой взгляд, самым простым способом было бы использовать PyCharm IDE и установить плагин ‘multirun’. Я попробовал много решений здесь, но это сработало для меня в конце концов!


-1

Kishan Vedia
28 Ноя 2019 в 06:54

Я делаю это в node.js (в Windows 10), открывая 2 отдельных экземпляра cmd и запуская каждую программу в каждом экземпляре.

Это имеет то преимущество, что запись в консоль легко видна для каждого сценария.

Я вижу, что в Python можно сделать то же самое: 2 оболочки.

Вы можете запустить несколько экземпляров оболочки IDLE / Python одновременно. Так что откройте IDLE и запустите код сервера, а затем снова откройте IDLE, который запустит отдельный экземпляр и затем запустит ваш клиентский код.


1

D.L
16 Мар 2018 в 19:38

Я работаю в Windows 7 с Python IDLE. У меня есть две программы,

# progA
while True:
    m = input('progA is running ')
    print (m)

И

# progB
while True:
    m = input('progB is running ')
    print (m)

Я открываю IDLE, а затем открываю файл progA.py. Я запускаю программу, и когда мне предлагают ввести данные, я ввожу "b" + <Enter>, а затем "c" + <Enter>

Я смотрю на это окно:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:UsersMikeAppDataLocalProgramsPythonPython36-32progA.py =
progA is running b
b
progA is running c
c
progA is running 

Затем я возвращаюсь в Windows Start и снова открываю IDLE, на этот раз открывая файл progB.py. Я запускаю программу, и когда мне предлагают ввести данные, я ввожу "x" + <Enter>, а затем "y" + <Enter>

Я смотрю на это окно:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:UsersMikeAppDataLocalProgramsPythonPython36-32progB.py =
progB is running x
x
progB is running y
y
progB is running 

Теперь две программы оболочки IDLE Python 3.6.3 работают одновременно, одна оболочка работает под управлением progA, а другая — под управлением progB.


0

CopyPasteIt
24 Фев 2018 в 03:55

Самое простое решение для одновременного запуска двух процессов Python — это запустить их из файла bash и указать каждому процессу перейти в фоновый режим с помощью оператора оболочки &.

python script1.py &
python script2.py &

Для более контролируемого способа параллельного запуска многих процессов перейдите в проект Supervisor или воспользуйтесь модуль многопроцессорной обработки для организации внутри Python.


25

logc
16 Фев 2015 в 20:25

Вы можете использовать Gnu-Parallel для одновременного запуска команд, работает в Windows, Linux / Unix .

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


0

Renjith Thankachan
24 Фев 2018 в 04:16

  • #1

IDLE (Python 3.10 64-bit
—————————-
Как запускать по очереди скрипты Python ?
1 скрипт отработал — записал результат в текстовый файл. Время его окончания не известно.
2 скрипт должен дождаться окончание работы 1 скрипта.
2 скрипт должен открыть этот текстовый файл и начинать работу.

  • #2

это файлы Py?
так без танцев разве нет так происходит?

  • #3

Да конечно. Эти скрипты: .py

Vershitel_sudeb


  • #4

пусть есть скрипты script1.py и script2.py, пусть script1 запускает после завершения script2, например
os.system(‘start script2.py’)

  • #5

СпасибоVershitel_sudeb
. Сработало. Жду окончания.
Ещё один вопрос: Как из файла — result.txt удалить дубликаты строк ?

  • #6

не понял, что сработало? то есть никаких import не надо, например:

Код:

import script1
script1.scr
 import script2
script2.scr

или это само собой разумеется?

  • #7

Спасибо.
Сработал скрипт.
Я просто в первый скрипт добавил строку: os.system(‘start 2_scan_udp.py’)
И более ничего не делал. Всё Ок.
—————————————
А это другой вопрос: Как из файла — result.txt удалить дубликаты строк ?

  • #8

Я просто в первый скрипт добавил строку: os.system(‘start 2_scan_udp.py’)

понял, а почему не с места где первый скрипт запускался? палка о двух конца и удобно и неудобно……

  • #9

Главное всё сработало. Спасибо.

  • #10

решил опробовать, добавил внизу файла

Код:

import os
os.system('form.py.py')

получил ошибку:
«form.py.py» �� ���� ����७��� ��� ���譥�
��������, �ᯮ��塞�� �ணࠬ��� ��� ������ 䠩���.
в чём ошибка? спасибо

  • #11

Ошибка в строке; os.system(‘form.py.py’) — два раза .py.py’ — не надо.
Надо так: os.system(‘form.py’)

  • #12

Надо так: os.system(‘form.py’)

ну да ошибся -исправил, ошибки нет и работы файла нет, или зависит что в нём?
начинается:

Код:

import tkinter as tk
class Main():
    def __init__(self):
    ..................

Vershitel_sudeb


  • #13

СпасибоVershitel_sudeb
. Сработало. Жду окончания.
Ещё один вопрос: Как из файла — result.txt удалить дубликаты строк ?

Python:

with open("file.txt") as f:
    text = 'n'.join(set(f.readlines()))
with open("file.txt", 'w') as f:
    f.write(text)

  • #15

актуально
в файле внизу: os.system(‘form.py’)
ошибки нет и работы файла нет, или зависит что в нём?
начинается:

Код:

import tkinter as tk
class Main():
def __init__(self):
..................

Vershitel_sudeb


  • #16

актуально
в файле внизу: os.system(‘form.py’)
ошибки нет и работы файла нет, или зависит что в нём?
начинается:

Код:

import tkinter as tk
class Main():
def __init__(self):
..................

А при запуске его вручную, он нормально работает? (form.py)

  • #17

Код:

from form import Main
m = Main()
print('Число из формы:', m.result)

да запускаю-она работает, шлёт верный ответ

Vershitel_sudeb


  • #18

Код:

from form import Main
m = Main()
print('Число из формы:', m.result)

да запускаю-она работает, шлёт верный ответ

Тогда скинь код обоих файлов, скорее всего там что-то не так

Vershitel_sudeb


  • #20

У тебя получилось два файла с функциями и классами, но ни одна из функций не вызывается и объектов классов не создается, нет смысла запускать файл form, он просто определяет класс.

Надо создать главный файл, и в него импортировать все остальное

P.S. в принципе нет смысла создавать функции
MsgBoxOk
MsgBoxYesNo
В tkinter есть такие методы по умолчанию: https://younglinux.info/tkinter/dialogbox

Понравилась статья? Поделить с друзьями:
  • Как запустить порт рояль 2 на windows 10
  • Как запустить про100 на windows 10
  • Как запустить откат системы windows 10 при включении
  • Как запустить несколько приложений на windows 10
  • Как запустить приостановленный процесс windows 10