开发者

Python: start many scripts at the same time

This program starts the first program. But I also want to run the second parallel. How can i start 开发者_开发问答two or more programs with a script?

# 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


try with the subprocess python module :

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'])

It will launch the 2 scripts in parallel (if your python.exe is in PATH).


To start several applications I'd recommend to use threading.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜