蟒蛇。如果程序停止,则必须启动新实例

时间:2011-10-23 14:45:55

标签: python multithreading process wait execute

Windows 7 64bit,python26

我运行一个Minecraft服务器,但有时程序因各种原因而停止运行。我希望在发生这种情况时启动一个新实例。

以下代码适用于notepad.exe,但即使之前没有停止,也会继续产生新的minecraft_servers。为什么?我该怎么办?

我是python的新手。

import Queue, thread, subprocess, time

results= Queue.Queue()
def process_waiter(popen, description, que):
    try: popen.wait()
    finally: que.put( (description, popen.returncode) )
process_count= 0

while True:
    proc1= subprocess.Popen( "C:\\Users\\Bo\\AppData\\Roaming\\.minecraf\\Minecraft_Server.exe")
    thread.start_new_thread(process_waiter,
    (proc1, "1 finished", results))
    process_count+= 1

    time.sleep(10)

    while process_count > 0:
        description, rc= results.get()
        print "job", description, "ended with rc =", rc
        process_count-= 1

1 个答案:

答案 0 :(得分:3)

目前还不清楚为什么进程重启器涉及线程化。 这对你有用吗?

while True:
    proc = subprocess.Popen("C:\\Users\\Bo\\AppData\\Roaming\\.minecraf\\Minecraft_Server.exe")
    proc.wait()
    print 'Minecraft_Server process terminated.  Restarting now'

建议:

  • 从几行有效的代码开始,然后添加功能
  • 使用线程代替线程
  • 不要将变量命名为“popen”,因为它与子流程中函数的名称相似。
  • 添加日志记录或打印语句,以便您可以了解脚本正在执行的操作
  • 使用任务管理器监控流程创建