2011-05-10 121 views
0

該程序啓動第一個程序。但我也想運行第二個並行。 如何用腳本啓動兩個或更多程序?Python:同時啓動多個腳本

# start many programs 
execfile('C:/Dokumente und Einstellungen/schnei17/Desktop/python/zeit/1.py') 
print 1 
execfile('C:/Dokumente und Einstellungen/schnei17/Desktop/python/zeit/2.py') 
print 2 
+5

你爲什麼不使用'subprocess'呢? – 2011-05-10 14:11:25

+1

'subprocess'使得這更容易,除非你需要在進程之間共享數據,在這種情況下,你會使用'多處理' – tMC 2011-05-10 14:14:03

回答

3

嘗試與子Python模塊:

import subprocess 
subprocess.Popen(["python.exe", 'C:/Dokumente und Einstellungen/schnei17/Desktop/python/zeit/1.py']) 
subprocess.Popen(["python.exe", 'C:/Dokumente und Einstellungen/schnei17/Desktop/python/zeit/2.py']) 

將並行推出2個腳本(如果您的python.exe是PATH)。

+0

我得到一個錯誤:WindowsError:[錯誤193](它不是一個win-32應用程序) – kame 2011-05-10 15:04:54

+0

我在腳本名稱前用python.exe調用更新,可以用python.exe的完整路徑替換python.exe – 2011-05-10 15:09:05

0

要啓動幾個應用程序,我建議使用線程。

shellcommands=("notepad.exe", 
       "calc.exe", 
       "mspaint.exe") 

import os 
import sys 
import time 
import datetime 
import threading 
import subprocess 

class ThreadClass(threading.Thread): 
    # Override Thread's __init__ method to accept the parameters needed: 

    def __init__ (self, command): 
     self.command = command 
     threading.Thread.__init__ (self) 

    def run(self): 
     now = datetime.datetime.now() 
     print "%s %s %s \n" % (self.getName(), self.command,now) 
     try: 
      subprocess.call(self.command, shell=True) 
     except Exception, err: 
      print "ERROR: %s\n" % str(err) 

for cmd in shellcommands: 
    t = ThreadClass(cmd) 
    t.start() 

sys.exit() 
+0

這會讓python也運行,並在控制檯上阻塞。除非這是有意的,否則最好使用子進程。 – Perkins 2012-09-29 02:25:22

+0

我必須得到:) – lukaz 2015-04-22 13:13:32