【问题标题】:how to run and exit python scripts from another python program?如何从另一个 python 程序运行和退出 python 脚本?
【发布时间】:2019-02-09 21:19:14
【问题描述】:

我希望在发送 on 请求时启动一个 python 文件,并在发送 off 请求后终止该 python 进程。我能够发送开和关请求,但无法运行其他 python 文件或从我编写的程序中杀死它。

我可以进行子进程调用,但我认为应该有一种方法可以在 python 脚本中调用其他 python 脚本,并且还有一种方法可以在完成它们的目的后终止这些脚本。

【问题讨论】:

  • 只要使用subprocess就可以杀了下等人

标签: python-3.x scripting


【解决方案1】:

我建议使用线程。

将python脚本中的所有代码写入函数doit(import语句除外) 然后导入它:

script.py 的内容:

import time

def doit(athread):
   while not athread.stopped():
      print("Hello World")
      time.sleep(1)

您的程序应如下所示:

import threading
import time
import thescript

class FuncThread(threading.Thread):
   def __init__(self, target):
      self.target=target
      super(FuncThread,self).__init__()
      self._stop_event=threading.Event()

   def stop(self):
      self._stop_event.set()

   def stopped(self):
      return self._stop_event.is_set()

   def run(self):
      self.target(self)

t1=FuncThread(thescript.doit)
t1.start()
time.sleep(5)
t1.stop()
t1.join()

你可以随时退出线程,我只是等了5秒然后调用了stop()方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    相关资源
    最近更新 更多