【问题标题】:How to decouple Python function as separate process? [duplicate]如何将 Python 函数解耦为单独的进程? [复制]
【发布时间】:2020-03-13 20:24:36
【问题描述】:

例如,我有一个函数 foo 和调用者函数。我需要 foo 去后台,设置锁定文件,设置一切,删除锁定文件。调用者必须调用 foo 并退出。我在考虑Subprocess 模块,但我看到它不能做我需要做的事情。 python-daemon 似乎很有希望,但我不需要它作为守护程序永远运行。

【问题讨论】:

    标签: python linux bash subprocess python-daemon


    【解决方案1】:

    可能想看看线程

    import threading
    
    def foo(my_args):
        # do something here
    
    def caller(some_args):
        # do some stuff
        foo_thread = threading.Thread(target=foo, args=some_args)
        foo_thread.start()
        # continue doing stuff
    
    caller()
    

    【讨论】:

      【解决方案2】:

      你可以在一个线程中守护你的函数:例如

      
      import threading
      import time
      
      def worker(snooze):
          print(f'snoozing {snooze} seconds')
          time.sleep(snooze)
      
      
      if __name__ == '__main___':
      
          task = threading.Thread(name='daemonize_worker', target=worker, args=(5, ))
          task.setDaemon(True)
          task.start()
      
      

      这会以一种守护进程的方式将工作人员在后台打盹 5 秒。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-23
        • 2011-05-02
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        • 1970-01-01
        相关资源
        最近更新 更多