【问题标题】:Python: start many scripts at the same timePython:同时启动多个脚本
【发布时间】:2011-05-10 14:08:34
【问题描述】:

这个程序启动第一个程序。但我也想运行第二个并行。 如何使用脚本启动两个或多个程序?

# 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

【问题讨论】:

  • 你为什么不使用subprocess呢?
  • subprocess 使这更容易,除非您需要在进程之间共享数据,在这种情况下您将使用multiprocessing

标签: python shell scripting


【解决方案1】:

尝试使用 subprocess 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 中)。

【讨论】:

  • 我收到一个错误:WindowsError: [Error 193](它不是一个 win-32 应用程序)
  • 我更新了脚本名称之前的 python.exe 调用,您可以将 python.exe 替换为您的 python 可执行文件的完整路径
【解决方案2】:

要启动多个应用程序,我建议使用线程。

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()

【讨论】:

  • 这将使 python 也运行,并在控制台上阻塞。除非这是有意为之,否则最好使用子流程。
猜你喜欢
  • 2021-02-25
  • 1970-01-01
  • 2015-10-25
  • 2021-06-06
  • 1970-01-01
  • 2018-12-04
相关资源
最近更新 更多